【问题标题】:Increment list index if condition如果条件增加列表索引
【发布时间】:2018-12-21 22:58:32
【问题描述】:

在遍历列表中的所有元素时,我想在遇到特定元素时跳过后面的两个元素,例如:

l1 = ["a", "b", "c", "d", "e", "f"]
for index, element in enumerate(l1):
    if element == "b":
        index = index + 2
    else:
        print(index, element)

0 a
2 c
3 d
4 e
5 f

【问题讨论】:

  • 你实际上用那个伪代码自己解决了这个问题。 @hancho 有答案。
  • 马克是更全面的答案。使用next(iterator, None) 在迭代器中跳过结果是非常惯用的。

标签: python list iteration


【解决方案1】:

更改索引不起作用,因为它是由枚举迭代器创建的。你可以自己在迭代器上调用next()

l1 = ["a", "b", "c", "d", "e", "f"]

iter  = enumerate(l1)
for index, element in iter:
    if element == "b":
        next(iter, None) # None avoids error if b is at the end
    else:
        print(index, element)

0个
3天
4电子
5 楼

【讨论】:

    【解决方案2】:
    l1 = ["a", "b", "c", "d", "e", "f"]
    index = 0
    while index < len(l1):
        if l1[index] == "b":
            index += 2
        else:
            print(index, l1[index])
            index += 1
    
    
    0 a
    3 d
    4 e
    5 f
    

    可以使用while循环。 index += 1 在如果你想要 2 c

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-17
      • 2020-09-28
      • 1970-01-01
      • 2018-04-29
      • 2020-03-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多