【问题标题】:How to split a list in n sized chunks, where n is an iterable list of integers?如何将列表拆分为 n 个大小的块,其中 n 是可迭代的整数列表?
【发布时间】:2019-04-06 03:08:09
【问题描述】:

我有一个单词列表和一个整数列表'n'。如何将单词列表拆分为“n”个大小的块(不均匀)?

例如

words = ['apple', 'orange', 'oof', 'banana', 'apple', 'cherries', 'tomato']
n = ['2', '1', '4']

输出:

[['apple', 'orange'], ['oof'], ['banana', 'apple', 'cherries', 'tomato']]

【问题讨论】:

    标签: python list split chunks


    【解决方案1】:

    另一个答案:

    output = []
    count = 0
    for i in range(len(n)):
        chunk_size = int(n[i])
        chunk = []
        for j in range(chunk_size):
            index = (i * j) + j
            chunk.append(words[count])
            count = count + 1
        output.append(chunk)
    
    print(output)
    

    【讨论】:

      【解决方案2】:

      您可以对iternext 使用列表推导:

      words = ['apple', 'orange', 'oof', 'banana', 'apple', 'cherries', 'tomato']
      n = ['2', '1', '4']
      new_words = iter(words)
      result = [[next(new_words) for _ in range(int(i))] for i in n]
      

      输出:

      [['apple', 'orange'], ['oof'], ['banana', 'apple', 'cherries', 'tomato']]
      

      【讨论】:

        【解决方案3】:

        简单的O(n)策略:

        words = ['apple', 'orange', 'oof', 'banana', 'apple', 'cherries', 'tomato']
        n = ['2', '1', '4']
        start = 0
        out = []
        for num in n:
            num = int(num)
            out.append(words[start:start+num])
            start += num
        

        【讨论】:

          【解决方案4】:

          如果您愿意导入 numpy 或 itertools,您可以创建一个包含累积总和的新列表,并将其用作索引来创建所需的输出:

          # itertools.accumulate
          from itertools import accumulate
          m = [0] + list(accumulate([0] + n))
          
          # numpy.cumsum
          import numpy as np
          m = np.cumsum([0] + n)
          
          # Create new list
          [words[i:j] for i, j in zip(m[:-1], m[1:])]
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2012-07-12
            • 1970-01-01
            • 2017-05-20
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多