【问题标题】:How to increment an iterator while iterating ("skipping some entries")?如何在迭代时增加迭代器(“跳过一些条目”)?
【发布时间】:2022-01-22 07:30:36
【问题描述】:

我遍历一个列表,在某些情况下我想跳过一些元素。一个典型的例子是我输出文件中的行,然后不输出特定行之间的行,最后输出其余的。

我想要实现的示例(代码无法按预期工作):

mylist = list(range(10))
for entry in mylist:
    if entry == 5:
        while entry < 8:
            next(mylist)    # ← this is the line I want to address
    else:
        print(entry)

我对输出的期望是 05,然后是 58,最后是 9

我得到的例外是TypeError: 'list' object is not an iterator(我以为是)。

有没有直接跳过迭代器条目的方法?

【问题讨论】:

  • @MichaelSzczesny:谢谢。我了解next(mylist) 将如何跳过条目5,但我看不到如何在一个会跳过几行的循环中运行此next(直到满足条件 - 在我的情况下为entry =&gt; 8

标签: python iterator


【解决方案1】:

mylist 是一个iterable,而不是一个迭代器,所以你不能直接在它上面调用next。但是你可以从中创建一个迭代器!

mylist = list(range(10))
mylist_iter = iter(mylist)
for entry in mylist_iter:
    if entry == 5:
        while next(mylist_iter) < 8:
            pass
    else:
        print(entry)
0
1
2
3
4
9

【讨论】:

    【解决方案2】:

    只需进行两项更改即可使您自己的解决方案按预期工作

    mylist = iter(range(10))
    for entry in mylist:
        if entry == 5:
            while entry < 8:
                entry = next(mylist)
        else:
            print(entry)
    

    输出

    0
    1
    2
    3
    4
    9
    

    【讨论】:

      【解决方案3】:

      如果你想任意向前移动它,你应该在 for 循环中使用迭代器。但是,您必须小心不要跳过值或超出数据。

      mylist = list(range(10))
      mylistIter = iter(mylist)
      for entry in mylistIter:
          if entry == 6: # to include 5, you must skip after processing it.
              try: 
                   while entry < 8: 
                       entry = next(mylistIter) 
              except StopIteration: break
          # do not use else: here or you'll skip item '8'
          print(entry)              
      
      0
      1
      2
      3
      4
      5
      8
      9
      

      或者,您可以使用continue 语句:

      mylist = list(range(10))
      for entry in mylist:
          if 5 < entry < 8: continue
          print(entry)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-06
        • 1970-01-01
        • 2013-01-27
        • 2015-08-16
        • 2011-05-06
        相关资源
        最近更新 更多