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

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

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

python: iterating through a dictionary with list values(python:遍历具有列表值的字典)
What is the difference between chain and chain.from_iterable in itertools?(itertools中chain和chain.from_iterable有什么区别?)
python JSON only get keys in first level(python JSON只获取第一级的键)
Iterate over n successive elements of list (with overlapping)(迭代列表的 n 个连续元素(重叠))
Loop problem while iterating through a list and removing recurring elements(遍历列表并删除重复元素时出现循环问题)
Elegant way to skip elements in an iterable(跳过可迭代元素的优雅方式)