从 python 中的表列表中提取列

Extract columns from list of tables in python

我有一个 table 的列表,其中每个 table 都是列表的列表。我想从每个 table 中提取列以获取列列表。一个例子应该说明:

input=[[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]],[[13,14,15],[16,17,18]]]
output=[[[1,4],[7,10],[13,16]],[[2,5],[8,11],[14,17]],[[3,6],[9,12],[15,18]]]

我知道我可能会使用多个 for 循环,但感觉应该有一个很好的衬垫来做到这一点。

我打算将结果赋给变量:

a,b,_=output

使用单个 table,我可以提取列:

>>>input=[[1,2,3],[4,5,6]]
>>>list(zip(*input))
[(1, 4), (2, 5), (3, 6)]

或分配:

>>>a,b,_=zip(*input)
>>>a
(1, 4)
>>>b
(2, 5)

但是对于table的列表,我一直做不到。以下是我尝试失败的一些方法:

>>>list(zip(*zip(*input)))
[([1, 2, 3], [4, 5, 6]), ([7, 8, 9], [10, 11, 12]), ([13, 14, 15], [16, 17, 18])]
>>>[list(zip(*inp)) for inp in input]
[[(1, 4), (2, 5), (3, 6)], [(7, 10), (8, 11), (9, 12)], [(13, 16), (14, 17), (15, 18)]]
>>>[[x,y,z] for x,y,z in [zip(*inp) for inp in input]]
#same as above
>>> [[x,y] for inp in input for x,y in zip(*inp)]
[[1, 4], [2, 5], [3, 6], [7, 10], [8, 11], [9, 12], [13, 16], [14, 17], [15, 18]]

而且 nested/unpacked 作业对我也不起作用:

>>>[[a,b,_]]=[zip(*inp) for inp in input]
ValueError: too many values to unpack (expected 1)
>>>[*a,*b,*_]=[[x,y] for x,y in [zip(*inp) for inp in input]]
SyntaxError: two starred expressions in assignment

是否有一条线可以完成我想做的事情?

编辑:请注意,虽然该示例具体为 3 table,每个 2 行和 3 列,但我的实际用例具有未知数量的 table 和行。

我最终在我的代码中使用了这一行:

list(zip(*[zip(*inp) for inp in input]))

您在最后一次尝试中接近成功。您还需要一个精心选择的嵌套级别。编辑:我添加了最后的 zip 步骤以获得所需的顺序。我还使用了那个“星号”符号来帮助展示如何扩展这个概念。

given = [[[1,2,3],[4,5,6]],
         [[7,8,9],[10,11,12]],
         [[13,14,15],[16,17,18]]]

f1 = [[[a, b] for a, b in zip(list1, list2)] for list1, list2 in given]
print(f1)
f2 = list(zip(*f1))
print(f2)

输出(为便于阅读而编辑)

[[[1, 4], [2, 5], [3, 6]], 
 [[7, 10], [8, 11], [9, 12]], 
 [[13, 16], [14, 17], [15, 18]]]

[([1, 4], [7, 10], [13, 16]),
 ([2, 5], [8, 11], [14, 17]),
 ([3, 6], [9, 12], [15, 18])]

第二个在中间层有元组而不是列表;可以吗?如果没有,你能修好吗? (留作学生练习...)