【发布时间】: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)在迭代器中跳过结果是非常惯用的。