如何按元素组合两个列表列表?

How to combine two lists of lists element-wise?

在Python中,我想以一种非常具体的方式组合列表的列表,但我还没有找到它。欢迎任何想法!

使用以下输入:

firstList = [[[1], [2], [3]], [[4], [5], [6]]]
secondList = [[[11], [12], [13]], [[14], [15], [16]]]

我想获得以下输出:

[[[1, 11], [2, 12], [3, 13]], [[4, 14], [5, 15], [6, 16]]]

我试过了:

[list(a) for a in zip(firstList, secondList)]

但是这个returns:

[[[[1], [2], [3]], [[11], [12], [13]]], [[[4], [5], [6]], [[14], [15], [16]]]]

我需要所需的输出以获得正确的格式,以便能够使用模块 tslearn 中的函数 TimeSeriesKMeans() 和二维时间序列

由于您有嵌套列表,因此您需要 zip 加倍查看列表。你可以这样做:

[[a + b for a, b in zip(x, y)] for x, y in zip(firstList, secondList)]

代码:

firstList = [[[1], [2], [3]], [[4], [5], [6]]]
secondList = [[[11], [12], [13]], [[14], [15], [16]]]

result = [[a + b for a, b in zip(x, y)] for x, y in zip(firstList, secondList)]
# [[[1, 11], [2, 12], [3, 13]], [[4, 14], [5, 15], [6, 16]]]

您也可以使用 itertools.chain:

from itertools import chain

result = [list(zip(chain(*l1), chain(*l2)))
          for l1, l2 in zip(firstList, secondList)]