元素明智合并列表python

时间:2018-06-13 05:44:49

标签: 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']]

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

3 个答案:

答案 0 :(得分:3)

以下代码将缩放

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_)])

答案 1 :(得分:1)

假设它们的大小相同:

a = []

for i in len(one):
    a.append([])
    for list in list_:
        a[-1] += list[1]

更好,在列表理解中:

import itertools    

[list(itertools.chain.from_iterable([list[x] for list in list_])) for x in len(one)]

答案 2 :(得分:1)

您可以将扩展可迭代解包运算符与zip方法结合使用。

from itertools import chain
one = [['hi', 'hello'], ['namaste']]
two = [['hi', 'bye'], ['namaste']]
three = [['hi', 'why'], ['bye']]
list_ = [one, two, three]
result = [list(chain.from_iterable(elem)) for elem in zip(*list_)]

输出

[['hi', 'hello', 'hi', 'bye', 'hi', 'why'], ['namaste', 'namaste', 'bye']]