简体   繁体   English

python转置除第一列之外的列表列表

[英]python transpose list of lists except first column

we can transpose list of list using 我们可以使用转置列表清单

map(list, zip(*l))

Can we change some thing in the above command to transpose the following list of lists, except the first element of inner list ? 我们可以在上面的命令中改变一些东西来转置下面的列表列表,除了内部列表的第一个元素吗?

l = [["item1",1,2,3],["item2",4,5,6],["item3",7,8,9]]

The result I'm looking for is 我正在寻找的结果是

r = [["item1",1,4,7],["item2",2,5,8],["item3",3,6,9]]

Alternative solution: 替代方案:

In [2]: it = [iter(x) for x in l]

In [3]: [list(x) for x in zip([next(x) for x in it], *it)]
Out[3]: [['item1', 1, 4, 7], ['item2', 2, 5, 8], ['item3', 3, 6, 9]]

First, this builds a list of iterators over sublists of l ( it ). 首先,这将构建lit )子列表上的迭代器列表。

[next(x) for x in it] advances each iterator in it and collects the results (first elements of lists) into a list, which is then zip ped together with previously incremented iterators from it . [next(x) for x in it]前进中的每个迭代it并收集结果(列表的第一元素)到一个列表中,然后将其zip与来自先前迭代递增一起PED it

There are easier ways if say you want to use pandas... 如果你想要使用熊猫,有更简单的方法......

headers = [item[0] for item in l]
data = [item[1:] for item in l]
r = map(list, zip(*data))
for i, item in enumerate(r):
    item.insert(0, headers[i])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM