单线检查迭代器是否产生至少一个元素?
问题描述
目前我正在这样做:
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)
.
相关文章