Sequence find function in Python(Python中的序列查找函数)
问题描述
如何在满足特定条件的序列中找到对象?
How do I find an object in a sequence satisfying a particular criterion?
列表理解和过滤器会遍历整个列表.唯一的选择是手工循环吗?
List comprehension and filter go through the entire list. Is the only alternative a handmade loop?
mylist = [10, 2, 20, 5, 50]
find(mylist, lambda x:x>10) # Returns 20
推荐答案
这是我使用的模式:
mylist = [10, 2, 20, 5, 50]
found = next(i for i in mylist if predicate(i))
或者,在 Python 2.4/2.5 中,next()
不是内置函数:
Or, in Python 2.4/2.5, next()
is a not a builtin:
found = (i for i in mylist if predicate(i)).next()
请注意,如果没有找到元素,next()
会引发 StopIteration
.在大多数情况下,这可能很好.您要求第一个元素,不存在这样的元素,因此程序可能无法继续.
Do note that next()
raises StopIteration
if no element was found. In most cases, that's probably good. You asked for the first element, no such element exists, and so the program probably cannot continue.
另一方面,如果您确实知道在这种情况下该怎么做,则可以为 next() 提供默认值:
If, on the other hand, you do know what to do in that case, you can supply a default to next():
conf_files = ['~/.foorc', '/etc/foorc']
conf_file = next((f for f in conf_files if os.path.exists(f)),
'/usr/lib/share/foo.defaults')
这篇关于Python中的序列查找函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python中的序列查找函数


基础教程推荐
- 修改列表中的数据帧不起作用 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 包装空间模型 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01