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

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

    Roll your own!

    def pairwise(iterable):
        it = iter(iterable)
        a = next(it, None)
    
        for b in it:
            yield (a, b)
            a = b
    

提交回复
热议问题