gpt4 book ai didi

python - 递增列表索引 if 条件

转载 作者:太空宇宙 更新时间:2023-11-04 08:29:39 26 4
gpt4 key购买 nike

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

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

最佳答案

更改索引不会起作用,因为它是由枚举迭代器创建的。您可以自己在迭代器上调用 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 d
4 e
5 f

关于python - 递增列表索引 if 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53891653/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com