問題描述
目前我正在這樣做:
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模板網!