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

标签 python

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

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

尽可能像 Python 一样。

最佳答案

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

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

all_matching = filter(matchCondition,lst)

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

关于python - 返回列表中匹配条件的第一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14366511/

相关文章:

python - 使用输入更改目录路径

python - 如何在 ActivePython 2.7 的 OSX 10.5 32 位上安装 OpenCV 2.2?

python - Heroku找不到pip(很奇怪)

python - Pandas:合并和比较数据帧

python - 如何在起始行数中添加字母?

python - ValueError : tf. 函数装饰函数试图在非第一次调用时创建变量

python - 如何在不将每个索引应用于每一行的情况下迭代数据框中的每一行?

python - 如何在 tkinter python 中的两个函数之间传递变量?

python - BeautifulSoup table 抓取只是有时会抓取

python - 在散点图中绘制标签