【问题标题】:Split a list into chunks of varying length将列表拆分为不同长度的块
【发布时间】:2012-11-16 11:36:21
【问题描述】:

给定一个项目序列和另一个块长度序列,我如何将序列拆分为所需长度的块?

a = range(10)
l = [3, 5, 2]
split_lengths(a, l) == [[0, 1, 2], [3, 4, 5, 6, 7], [8, 9]]

理想情况下,解决方案可以同时使用 al 作为通用可迭代对象,而不仅仅是列表。

【问题讨论】:

    标签: python list iterator


    【解决方案1】:

    在列表的迭代器上使用itertools.islice

    In [12]: a = range(10)
    
    In [13]: b = iter(a)
    
    In [14]: from itertools import islice
    
    In [15]: l = [3, 5, 2]
    
    In [16]: [list(islice(b, x)) for x in l]
    Out[16]: [[0, 1, 2], [3, 4, 5, 6, 7], [8, 9]]
    

    或:

    In [17]: b = iter(a)
    
    In [18]: [[next(b) for _ in range(x)] for x in l]
    Out[18]: [[0, 1, 2], [3, 4, 5, 6, 7], [8, 9]]
    

    【讨论】:

      【解决方案2】:
      def split_lengths(a,l):
          resultList = []
          index=0
      
          for length in l:
              resultList.append(a[index : index + length])
              index = index + length
      
          retun resultList
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-10-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-29
        • 1970-01-01
        • 2019-11-07
        相关资源
        最近更新 更多