One-liner to check whether an iterator yields at least one element?(单线检查迭代器是否产生至少一个元素?)
问题描述
目前我正在这样做:
try:
something = iterator.next()
# ...
except StopIteration:
# ...
但我想要一个可以放在简单 if
语句中的表达式.有什么内置的东西可以让这段代码看起来不那么笨拙吗?
But I would like an expression that I can place inside a simple if
statement.
Is there anything built-in which would make this code look less clumsy?
any()
如果可迭代对象为空,则返回 False
,但如果不是,它可能会遍历所有项目.我只需要它来检查第一项.
any()
returns False
if an iterable is empty, but it will potentially iterate over all the items if it's not.
I only need it to check the first item.
有人问我要做什么.我编写了一个执行 SQL 查询并产生结果的函数.有时当我调用这个函数时,我只想知道查询是否返回任何内容并根据它做出决定.
Someone asks what I'm trying to do. I have written a function which executes an SQL query and yields its results. Sometimes when I call this function I just want to know if the query returned anything and make a decision based on that.
推荐答案
any
如果第一个元素为 True,则不会超出第一个元素.如果迭代器产生错误的结果,您可以编写 any(True for _ in iterator)
.
any
won't go beyond the first element if it's True. In case the iterator yields something false-ish you can write any(True for _ in iterator)
.
这篇关于单线检查迭代器是否产生至少一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:单线检查迭代器是否产生至少一个元素?


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