在Python中转置嵌套列表
我喜欢把这个列表中的每个项目移动到另一个嵌套列表可以帮助我吗?
a = [['AAA', '1', '1', '10', '92'], ['BBB', '262', '56', '238', '142'], ['CCC', '86', '84', '149', '30'], ['DDD', '48', '362', '205', '237'], ['EEE', '8', '33', '96', '336'], ['FFF', '39', '82', '89', '140'], ['GGG', '170', '296', '223', '210'], ['HHH', '16', '40', '65', '50'], ['III', '4', '3', '5', '2']]
最后我会列出这样的名单:
[['AAA', 'BBB', 'CCC', 'DDD', 'EEE', 'FFF'.....], ['1', '262', '86', '48', '8', '39', ...], ['1', '56', '84', '362', '33', '82', ...], ['10', '238', '149', '205', '96', '89', ...], ... ...]
使用带有*
和zip
:
>>> map(list, zip(*a)) [['AAA', 'BBB', 'CCC', 'DDD', 'EEE', 'FFF', 'GGG', 'HHH', 'III'], ['1', '262', '86', '48', '8', '39', '170', '16', '4'], ['1', '56', '84', '362', '33', '82', '296', '40', '3'], ['10', '238', '149', '205', '96', '89', '223', '65', '5'], ['92', '142', '30', '237', '336', '140', '210', '50', '2']]
注意map
在Python 3中返回一个map对象,所以你需要list(map(list, zip(*a)))
使用zip(*...)
list comprehension
,这将在Python 2和Python 3中都能正常工作。
[list(x) for x in zip(*a)]
NumPy方式:
>>> import numpy as np >>> np.array(a).T.tolist() [['AAA', 'BBB', 'CCC', 'DDD', 'EEE', 'FFF', 'GGG', 'HHH', 'III'], ['1', '262', '86', '48', '8', '39', '170', '16', '4'], ['1', '56', '84', '362', '33', '82', '296', '40', '3'], ['10', '238', '149', '205', '96', '89', '223', '65', '5'], ['92', '142', '30', '237', '336', '140', '210', '50', '2']]
通过列表理解:
[[x[i] for x in mylist] for i in range(len(mylist[0]))]
你也可以这样做:
row1 = [1,2,3] row2 = [4,5,6] row3 = [7,8,9] matrix = [row1, row2, row3] trmatrix = [[row[0] for row in matrix],[row[1] for row in matrix], [row[2] for row in matrix]]