Python 2.6以上
next(iter(your_list), None)
如果
your_list可以
None:
next(iter(your_list or []), None)
Python 2.4
def get_first(iterable, default=None): if iterable: for item in iterable: return item return default
例:
x = get_first(get_first_list())if x: ...y = get_first(get_second_list())if y: ...
另一个选择是内联以上函数:
for x in get_first_list() or []: # process x break # process at most one itemfor y in get_second_list() or []: # process y break
为了避免
break您可以写:
for x in yield_first(get_first_list()): x # process xfor y in yield_first(get_second_list()): y # process y
哪里:
def yield_first(iterable): for item in iterable or []: yield item return



