一行检查迭代器是否产生至少一个元素? [英] One-liner to check whether an iterator yields at least one element?

查看:84
本文介绍了一行检查迭代器是否产生至少一个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我正在这样做:

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()如果iterable为空,则返回 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(迭代器中的_为真)

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).

这篇关于一行检查迭代器是否产生至少一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆