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

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

    A basic solution:

    def neighbors( list ):
      i = 0
      while i + 1 < len( list ):
        yield ( list[ i ], list[ i + 1 ] )
        i += 1
    
    for ( x, y ) in neighbors( list ):
      print( x, y )
    

提交回复
热议问题