我有一个单词列表和一个整数'n'列表。如何将单词列表分成n个大小的块(不均匀)?
例如
words = ['apple', 'orange', 'oof', 'banana', 'apple', 'cherries', 'tomato']
n = ['2', '1', '4']
输出:
[['apple', 'orange'], ['oof'], ['banana', 'apple', 'cherries', 'tomato']]
答案 0 :(得分:2)
另一个答案:
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)
答案 1 :(得分:1)
您可以对iter
和next
使用列表推导:
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']]
答案 2 :(得分:1)
简单的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
答案 3 :(得分:0)
如果您愿意导入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:])]