我有一个很大的列表列表,例如:
list = [['a'], ['b'], ['c'], ['1234'], ['d'], ['e'], ['g'], ['h'], ['i'], ['56']]
我想将每 5 个列表组合成一个元素列表,依此类推。我在一个列表中总共有 150995 个列表。
预期输出:
new_list = [['a' , 'b', 'c', '1234', 'd'], ['e', 'g', 'h', 'i', '56']]
我尝试使用以下代码。但它被扁平化为一个列表。
list(zip(*list)[0])
我该怎么做?
您基本上想要对大小均匀的列表 block 进行分组。可以使用 itertools.chain
并使用 range
和 5 步进行切片
import itertools
lst = [['a'], ['b'], ['c'], ['1234'], ['d'], ['e'], ['g'], ['h'], ['i'], ['56']]
result = [list(itertools.chain.from_iterable(itertools.islice(lst,i,i+5))) for i in range(0,len(lst),5)]
print(result)
结果:
[['a', 'b', 'c', '1234', 'd'], ['e', 'g', 'h', 'i', '56']]
注意事项:
- 使用
itertools.islice
避免标准 lst[i:i+5]
切片创建无用的 list
对象
- 即使元素数量不能被 5 整除,它也能正常工作。
我是一名优秀的程序员,十分优秀!