在python中按列连接数组

我有一个数组列表,其中每个数组都是一个列表列表。我想把它变成一个包含所有列的数组。我试过使用 for 循环来完成这项工作,但感觉它在列表理解中应该是可行的。有没有一个很好的单线可以做到这一点?


    Example Input: [[[1,2],[3,4],[5,6]],[[7,8],[9,10],[11,12]]]

    

    Desired Output: [[1,2,7,8],[3,4,9,10],[5,6,11,12]]

注意:示例在主列表中只有两个数组,但我的实际数据有更多,所以我正在寻找适用于 N 个子数组的东西。


编辑:试图解决这个问题的例子


适用于两个但不概括:


[input[0][i]+input[1][i] for i in range(len(input[0]))]

这些不起作用,但显示了这个想法:


[[element for table in input for element in row] for row in table]

[[*imput[j][i] for j in range(len(input))] for i in range(len(input[0]))]

编辑:仅使用列表理解和压缩的选定答案,但所有答案(截至目前)都有效,因此请使用最适合您的风格/用例的答案。


陪伴而非守候
浏览 166回答 4
4回答

Smart猫小萌

您可以从标准列表扁平化模式和中概括这一点zip:>>> L = [[[1,2],[3,4],[5,6]],[[7,8],[9,10],[11,12]]]>>> list([y for z in x for y in z] for x in zip(*L))[[1, 2, 7, 8], [3, 4, 9, 10], [5, 6, 11, 12]]>>> L = [[[1,2],[3,4],[5,6]],[[7,8],[9,10],[11,12]],[[13,14],[15,16],[17,18]]]>>> list([y for z in x for y in z] for x in zip(*L))[[1, 2, 7, 8, 13, 14], [3, 4, 9, 10, 15, 16], [5, 6, 11, 12, 17, 18]]

开满天机

如果你不介意它是列表中的一个元组。你也可以尝试:from itertools import chaina = [[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10], [11, 12]], [[13, 14], [15, 16], [17, 18]]]output = list(map(list, map(chain.from_iterable, zip(*a))))# [[1, 2, 7, 8, 13, 14], [3, 4, 9, 10, 15, 16], [5, 6, 11, 12, 17, 18]]

紫衣仙女

这是一种方法:initial = [[[1,2],[3,4],[5,6]],[[7,8],[9,10],[11,12]]]output = [a+b for a, b in zip(*initial)]print(output)如果您有更多列表,这也适用:import itertoolsinitial = [[[1,2],[3,4],[5,6]],[[7,8],[9,10],[11,12]],[[13,14],[15,16],[17,18]]]output = [list(itertools.chain.from_iterable(values)) for values in zip(*initial)]print(output)

米脂

这样就可以了,我将您的输入命名为first:[*map(lambda x: list(i for s in x for i in s), zip(*first))][[1, 2, 7, 8], [3, 4, 9, 10], [5, 6, 11, 12]]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python