虽然遍历列表中的所有元素,但我想在遇到特定元素时跳过后面的两个元素,例如:
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
答案 0 :(得分:3)
更改索引将无法进行,因为它是由枚举迭代器创建的。您可以自己在迭代器上调用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 a
3天
4 e
5楼
答案 1 :(得分: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