Python 返回列表中匹配条件的第一项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14366511/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Return the first item in a list matching a condition
提问by user1008636
I have a function. matchCondition(a), which takes an integer and either returns True or False.
我有一个功能。matchCondition(a),它接受一个整数并返回 True 或 False。
I have a list of 10 integers. I want to return the first item in the list (in the same order as the original list) that has matchConditionreturning True.
我有一个 10 个整数的列表。我想返回列表中matchCondition返回 True的第一项(与原始列表的顺序相同)。
As pythonically as possible.
尽可能pythonically。
采纳答案by mgilson
next(x for x in lst if matchCondition(x))
should work, but it will raise StopIterationif none of the elements in the list match. You can suppress that by supplying a second argument to next:
应该可以工作,但StopIteration如果列表中的元素都不匹配,它会引发。您可以通过向 提供第二个参数来抑制它next:
next((x for x in lst if matchCondition(x)), None)
which will return Noneif nothing matches.
None如果没有匹配项,它将返回。
Demo:
演示:
>>> 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
Finally, just for completeness, if you want allthe items that match in the list, that is what the builtin filterfunction is for:
最后,为了完整性,如果您想要列表中匹配的所有项目,这就是内置filter函数的用途:
all_matching = filter(matchCondition,lst)
In python2.x, this returns a list, but in python3.x, it returns an iterable object.
在 python2.x 中,它返回一个列表,但在 python3.x 中,它返回一个可迭代对象。
回答by Ashwini Chaudhary
Use the breakstatement:
使用break语句:
for x in lis:
if matchCondition(x):
print x
break #condition met now break out of the loop
now xcontains the item you wanted.
现在x包含您想要的项目。
proof:
证明:
>>> for x in xrange(10):
....: if x==5:
....: break
....:
>>> x
>>> 5

