Iterate a list as pair (current, next) in Python

前端 未结 10 1729
隐瞒了意图╮
隐瞒了意图╮ 2020-11-21 22:54

I sometimes need to iterate a list in Python looking at the \"current\" element and the \"next\" element. I have, till now, done so with code like:

for curre         


        
10条回答
  •  无人及你
    2020-11-21 23:19

    I’m just putting this out, I’m very surprised no one has thought of enumerate().

    for (index, thing) in enumerate(the_list):
        if index < len(the_list):
            current, next_ = thing, the_list[index + 1]
            #do something
    

提交回复
热议问题