gpt4 book ai didi

python - 如何在 python 中组合列表中的每 5 个列表?

转载 作者:太空宇宙 更新时间:2023-11-03 14:43:18 25 4
gpt4 key购买 nike

我有一个很大的列表列表,例如:

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 整除,它也能正常工作。

关于python - 如何在 python 中组合列表中的每 5 个列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51584415/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com