单线检查迭代器是否产生至少一个元素?

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

问题描述

目前我正在这样做:

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

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

上一篇:迭代器和索引可访问的 Python 类 下一篇:'numpy.float64' 对象不可迭代

相关文章

最新文章