返回符合条件的列表中的第一项

返回符合条件的列表中的第一项,第1张

返回符合条件的列表中的第一项

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中,它返回一个可迭代的对象。



欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5654855.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-16
下一篇2022-12-16

发表评论

登录后才能评论

评论列表(0条)

    保存