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

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

    Since the_list[1:] actually creates a copy of the whole list (excluding its first element), and zip() creates a list of tuples immediately when called, in total three copies of your list are created. If your list is very large, you might prefer

    from itertools import izip, islice
    for current_item, next_item in izip(the_list, islice(the_list, 1, None)):
        print(current_item, next_item)
    

    which does not copy the list at all.

提交回复
热议问题