Skip to main content
 首页 » 编程设计

python之递增列表索引 if 条件

2025年05月04日21myhome

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

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