【问题标题】:Iterate every 2 elements from list at a time一次迭代列表中的每 2 个元素
【发布时间】:2014-03-12 05:38:39
【问题描述】:

列表为 ,

l = [1,2,3,4,5,6,7,8,9,0]

如何一次迭代每两个元素?

我正在尝试这个,

for v, w in zip(l[:-1],l[1:]):
    print [v, w]

得到输出就像,

[1, 2]
[2, 3]
[3, 4]
[4, 5]
[5, 6]
[6, 7]
[7, 8]
[8, 9]
[9, 0]

预期输出是

[1,2]
[3, 4]
[5, 6]
[7, 8]
[9,10]

【问题讨论】:

    标签: python list python-2.7


    【解决方案1】:

    你可以使用iter:

    >>> seq = [1,2,3,4,5,6,7,8,9,10]
    >>> it = iter(seq)
    >>> for x in it:
    ...     print (x, next(it))
    ...     
    [1, 2]
    [3, 4]
    [5, 6]
    [7, 8]
    [9, 10]
    

    您也可以使用来自 itertools 的 grouper recipe

    >>> from itertools import izip_longest
    >>> def grouper(iterable, n, fillvalue=None):
    ...         "Collect data into fixed-length chunks or blocks"
    ...         # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    ...         args = [iter(iterable)] * n
    ...         return izip_longest(fillvalue=fillvalue, *args)
    ... 
    >>> for x, y in grouper(seq, 2):
    ...     print (x, y)
    ...     
    [1, 2]
    [3, 4]
    [5, 6]
    [7, 8]
    [9, 10]
    

    【讨论】:

      【解决方案2】:

      您可以按照自己的方式进行,只需在切片中添加一个步骤部分以使两个切片都跳过一个数字:

      for v, w in zip(l[::2],l[1::2]):  # No need to end at -1 because that's the default
          print [v, w]
      

      但我喜欢辅助生成器:

      def pairwise(iterable):
          i = iter(iterable)
          while True:
             yield i.next(), i.next()
      
      for v, w in pairwise(l):
          print v, w
      

      【讨论】:

        【解决方案3】:

        有什么问题:

        l = [1, 2, 3, 4, 5, 6, 7, 8]
        for j in range(0, len(l), 2):
                print(l[j: j + 2])
        
        [1, 2]
        [3, 4]
        [5, 6]
        [7, 8]
        

        假设列表有偶数个元素

        【讨论】:

          【解决方案4】:

          一个解决方案是

          for v, w in zip(l[::2],l[1::2]):
              print [v, w]
          

          【讨论】:

            【解决方案5】:
            In [180]: lst = range(1,11)
            
            In [181]: for i in zip(*[iter(lst)]*2):
               .....:     print i
               .....:
            (1, 2)
            (3, 4)
            (5, 6)
            (7, 8)
            (9, 10)
            

            【讨论】:

              【解决方案6】:
              >>> l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 
              >>> map(None,*[iter(l)]*2)
              [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)]
              >>>
              

              【讨论】:

              • 如何使其成为列表列表而不是元组列表?
              • l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] l2=map(None,*[iter(l)]*2) print(l2 ) 给出地图对象而不是 k,v 对。 print(list(l2)) 给出 TypeError: 'NoneType' object is not callable
              【解决方案7】:

              我知道这是一个老问题,只是一种不同的方法。

              l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 
              chunks = [l[x:x+2] for x in range(0,len(l),2)]
              print(chunks)
              

              【讨论】:

                【解决方案8】:

                对于那些想要通过很长的步骤浏览列表并且不想预先使用大量内存的人来说,您可以这样做。

                Python 2.7:

                import itertools
                
                def step_indices(length, step):
                    from_indices = xrange(0, length, step)
                    to_indices = itertools.chain(xrange(step, length, step), [None])
                    for i, j in itertools.izip(from_indices, to_indices):
                        yield i, j
                
                the_list = range(1234)
                for i, j in step_indices(len(the_list), 100):
                    up_to_100_values = the_list[i:j]
                

                Python 3:

                import itertools
                
                def step_indices(length, step):
                    from_indices = range(0, length, step)
                    to_indices = itertools.chain(range(step, length, step), [None])
                    for i, j in zip(from_indices, to_indices):
                        yield i, j
                
                the_list = list(range(1234))
                for i, j in step_indices(len(the_list), 100):
                    up_to_100_values = the_list[i:j]
                

                【讨论】:

                  【解决方案9】:

                  map 的另一个解决方案(语法与其他答案略有不同)。在具有奇数个元素的列表中,最后一个元素与None 配对:

                  >>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
                  >>> map(None, a[::2], a[1::2])
                  [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10), (11, None)]
                  

                  您可以修改函数以返回例如列表而不是元组:

                  >>> map(lambda x,y:[x,y], a[::2], a[1::2])
                  [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, None]]
                  
                  >>> for e in map(lambda x,y:[x,y], a[::2], a[1::2]):
                  ...     print e
                  ... 
                  [1, 2]
                  [3, 4]
                  [5, 6]
                  [7, 8]
                  [9, 10]
                  [11, None]
                  

                  编辑:此解决方案仅适用于 Python 2.x。

                  【讨论】:

                    猜你喜欢
                    • 1970-01-01
                    • 1970-01-01
                    • 2020-08-27
                    • 1970-01-01
                    • 2010-12-27
                    • 1970-01-01
                    • 1970-01-01
                    • 2015-12-25
                    相关资源
                    最近更新 更多