使用Python

时间:2017-06-29 13:32:25

标签: python python-3.x

如果我有一个包含多个列表的列表(为简单起见3,但实际上我的数量非常大):

list = [[1,a,2],[3,b,4],[5,c,6]]

如何使用Python获取基于其位置组合原始列表项的新列表?

new_list = [[1,3,5],[a,b,c],[2,4,6]]

我一直在尝试“列表”上的zip功能,但它不起作用,我做错了什么?

3 个答案:

答案 0 :(得分:2)

这就是你想要的。

mylist = [[1,"a",2],[3,"b",4],[5,"c",6]]
mylist2 = list(map(list, zip(*mylist)))

请不要使用列表或任何其他built-in作为变量名称。

Try it online!

list(map(list, zip(*mylist)))

                   *mylist    -- unpacks the list
               zip(*mylist)   -- creates an iterable of the unpacked list, 
                                 with the i-th element beeing a tuple 
                                 containing all i-th elements of each element of *mylist
         list                 -- Is the built-in function list()
     map( f  ,   iter      )  -- Applys a function f to all elements of an iterable iter
list(                       ) -- Creates a list from whatever is inside.

答案 1 :(得分:1)

您可以使用zip:

a = 1
b = 2
c = 3
l = [[1,a,2],[3,b,4],[5,c,6]]

new_l = list(map(list, zip(*l)))

输出:

[[1, 3, 5], [1, 2, 3], [2, 4, 6]]

请注意,变量现在显示在new_l

的第二个元素中

答案 2 :(得分:0)

您可以使用zip,同时谨慎使用built-in functions作为变量名称。

*ngFor

输出

l = [[1,a,2],[3,b,4],[5,c,6]]
list(zip(*l))
相关问题