首页 > 解决方案 > 列表python的元素明智合并

问题描述

要合并两个列表的元素,如下所示,非常简单:

one = [['hi', 'hello'], ['namaste']]
two = [['hi', 'bye'], ['namaste']]

[m+n for m,n in zip(one,two)]

但是,如果我有一个大于长度 2 的列表,怎么办?例如,连接以下列表列表中的每个元素:

three = [['hi', 'why'], ['bye']]
list_ = [one, two, three]

我想要一个像这样的输出:[['hi', 'hello', 'hi', 'bye', 'hi', 'why'], ['namaste', 'namaste', 'bye']]

如何以可扩展的方式完成此操作,甚至可以使用list_长度为 10 的 a?

标签: python

解决方案


以下代码将缩放

from itertools import chain
out = []
for each in zip(*list_):
    out.append(list(chain.from_iterable(each)))

或单班轮

print([list(chain.from_iterable(each)) for each in zip(*list_)])

推荐阅读