23

我有一个功能。matchCondition(a),它接受一个整数并返回 True 或 False。

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

尽可能像 Python 一样。

4

2 回答 2

55
next(x for x in lst if matchCondition(x)) 

StopIteration应该可以,但是如果列表中没有任何元素匹配,它将引发。您可以通过提供第二个参数来抑制它next

next((x for x in lst if matchCondition(x)), None)

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

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

all_matching = filter(matchCondition,lst)

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

于 2013-01-16T19:45:57.373 回答
5

使用break语句:

for x in lis:
  if matchCondition(x):
     print x
     break            #condition met now break out of the loop

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

证明:

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

>>> x
>>> 5
于 2013-01-16T19:47:08.447 回答