[英]How to combine two lists of lists element-wise?
In Python, I would like to combine lists of lists in a very specific way, but I could not find it yet.在 Python 中,我想以一种非常具体的方式组合列表列表,但我还没有找到。 Any ideas are welcome!欢迎任何想法!
With the following input:使用以下输入:
firstList = [[[1], [2], [3]], [[4], [5], [6]]]
secondList = [[[11], [12], [13]], [[14], [15], [16]]]
I would like to get the following output:我想得到以下 output:
[[[1, 11], [2, 12], [3, 13]], [[4, 14], [5, 15], [6, 16]]]
I tried:我试过了:
[list(a) for a in zip(firstList, secondList)]
but this returns:但这会返回:
[[[[1], [2], [3]], [[11], [12], [13]]], [[[4], [5], [6]], [[14], [15], [16]]]]
I need the desired output to get the correct format to be able to use the function TimeSeriesKMeans()
from the module tslearn
with time series in 2 dimensions我需要所需的 output 以获得正确的格式,以便能够使用模块tslearn
中的 function TimeSeriesKMeans()
和二维时间序列
Since you are having nested lists, you need to double zip
through your list.由于您有嵌套列表,因此您需要将zip
通过您的列表加倍。 You can do:你可以做:
[[a + b for a, b in zip(x, y)] for x, y in zip(firstList, secondList)]
Code :代码:
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]]]
You could also use itertools.chain
:您也可以使用itertools.chain
:
from itertools import chain
result = [list(zip(chain(*l1), chain(*l2)))
for l1, l2 in zip(firstList, secondList)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.