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

前端 未结 10 1706
隐瞒了意图╮
隐瞒了意图╮ 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:05

    Iterating by index can do the same thing:

    #!/usr/bin/python
    the_list = [1, 2, 3, 4]
    for i in xrange(len(the_list) - 1):
        current_item, next_item = the_list[i], the_list[i + 1]
        print(current_item, next_item)
    

    Output:

    (1, 2)
    (2, 3)
    (3, 4)
    

提交回复
热议问题