gpt4 book ai didi

python - 用于检测空序列的更好的 for 循环语法?

转载 作者:太空狗 更新时间:2023-10-29 18:02:40 26 4
gpt4 key购买 nike

有没有更好的写法:

   row_counter = 0
for item in iterable_sequence:
# do stuff with the item

counter += 1

if not row_counter:
# handle the empty-sequence-case

请记住,我不能使用 len(iterable_sequence) 因为 1) 并非所有序列的长度都是已知的; 2) 在某些情况下,调用 len() 可能会触发将序列的项目加载到内存中(就像 sql 查询结果一样)。

我问的原因是我只是想知道是否有办法使上面的内容更简洁和惯用。我正在寻找的是:

for item in sequence:
#process item
*else*:
#handle the empty sequence case

(假设这里的“else”只对空序列起作用,我知道它不起作用)

最佳答案

for item in iterable:
break
else:
# handle the empty-sequence-case here

或者

item = next(iterator, sentinel)
if item is sentinel:
# handle the empty-sequence-case here

在每种情况下,如果存在一项,则消耗一项。


评论中提到的 empty_adapter() 实现示例:

def empty_adaptor(iterable, sentinel=object()):
it = iter(iterable)
item = next(it, sentinel)
if item is sentinel:
return None # empty
else:
def gen():
yield item
for i in it:
yield i
return gen()

您可以按如下方式使用它:

it = empty_adaptor(some_iter)
if it is not None:
for i in it:
# handle items
else:
# handle empty case

为一般情况引入空序列的特殊情况似乎错误。对于特定领域的问题应该有更好的解决方案。

关于python - 用于检测空序列的更好的 for 循环语法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4557255/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com