为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

德玛西亚99 2021-09-23 09:47:16
在迭代列表中的所有元素时,我想在遇到特定元素时跳过后面的两个元素,例如:l1 = ["a", "b", "c", "d", "e", "f"]for index, element in enumerate(l1):    if element == "b":        index = index + 2    else:        print(index, element)0 a2 c3 d4 e5 f
查看完整描述

2 回答

?
神不在的星期二

TA贡献1963条经验 获得超6个赞

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


查看完整回答
反对 回复 2021-09-23
?
12345678_0001

TA贡献1802条经验 获得超5个赞

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


查看完整回答
反对 回复 2021-09-23
  • 2 回答
  • 0 关注
  • 190 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号