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

Dmi*_* B. 11 python syntax for-loop

是否有更好的方法来编写以下内容:

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

      counter += 1

   if not row_counter:
      # handle the empty-sequence-case
Run Code Online (Sandbox Code Playgroud)

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

我问的原因是,我只是好奇是否有办法让上面更简洁和惯用.我正在寻找的是:

for item in sequence:
   #process item
*else*:
   #handle the empty sequence case
Run Code Online (Sandbox Code Playgroud)

(假设"else"在这里仅适用于空序列,我知道它没有)

jfs*_*jfs 8

for item in iterable:
    break
else:
    # handle the empty-sequence-case here
Run Code Online (Sandbox Code Playgroud)

要么

item = next(iterator, sentinel)
if item is sentinel:
   # handle the empty-sequence-case here   
Run Code Online (Sandbox Code Playgroud)

在每种情况下,如果存在,则消耗一个项目.


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()
Run Code Online (Sandbox Code Playgroud)

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

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

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

  • 我需要处理列表中的所有项目,而不仅仅是第一个项目.为了处理剩下的项目,我需要设置另一个for循环,这将使整个解决方案比原始解决方案更简洁. (2认同)