如果条件,则增加列表索引

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


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


德玛西亚99
浏览 191回答 2
2回答

神不在的星期二

更改索引不会起作用,因为它是由枚举迭代器创建的。您可以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 a3 d4 e5 f

12345678_0001

l1 = ["a", "b", "c", "d", "e", "f"]index = 0while index < len(l1):&nbsp; &nbsp; if l1[index] == "b":&nbsp; &nbsp; &nbsp; &nbsp; index += 2&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; print(index, l1[index])&nbsp; &nbsp; &nbsp; &nbsp; index += 10 a3 d4 e5 f可以使用while循环。index += 1如果你想要 2 c
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python