返回与条件匹配的列表中的第一项

use*_*636 19 python

我有一个功能.matchCondition(a),取整数并返回True或False.

我有一个10个整数的列表.我想返回列表中的第一个项目(与原始列表的顺序相同),matchCondition返回True.

尽可能诡异.

mgi*_*son 47

next(x for x in lst if matchCondition(x)) 
Run Code Online (Sandbox Code Playgroud)

应该工作,但StopIteration如果列表中没有任何元素匹配,它将会提升.你可以通过提供第二个参数来抑制它next:

next((x for x in lst if matchCondition(x)), None)
Run Code Online (Sandbox Code Playgroud)

None如果没有匹配将返回.

演示:

>>> next(x for x in range(10) if x == 7)  #This is a silly way to write 7 ...
7
>>> next(x for x in range(10) if x == 11)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> next((x for x in range(10) if x == 7), None)
7
>>> print next((x for x in range(10) if x == 11), None)
None
Run Code Online (Sandbox Code Playgroud)

最后,为了完整性,如果你想要列表中匹配的所有项目,那就是内置filter函数的用途:

all_matching = filter(matchCondition,lst)
Run Code Online (Sandbox Code Playgroud)

在python2.x中,这将返回一个列表,但在python3.x中,它返回一个可迭代对象.

  • 有趣的应用`next`,我从来没有想过它. (2认同)

Ash*_*ary 5

使用break语句:

for x in lis:
  if matchCondition(x):
     print x
     break            #condition met now break out of the loop
Run Code Online (Sandbox Code Playgroud)

现在x包含您想要的项目。

证明:

>>> for x in xrange(10):
   ....:     if x==5:
   ....:         break
   ....:         

>>> x
>>> 5
Run Code Online (Sandbox Code Playgroud)

  • 这很好,除非没有任何条件匹配,否则它只返回“集合[-1]” (2认同)