簡體   English   中英

使用Python將列表列表中的條目壓縮在一起

[英]Zipping together entries of a list of lists using Python

如果我有一個包含多個列表的列表(為簡單起見3,但實際上數量很多):

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

如何使用Python根據列表的位置獲取將原始列表項組合在一起的新列表列表?

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

我一直在嘗試“列表”上的zip功能,但是它不起作用,我在做什么錯?

這就是您想要的。

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

請不要使用列表或任何其他內置變量名稱。

在線嘗試!

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.

您可以使用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的第二個元素中

您可以使用zip ,也請記住,將內置函數用作變量名是一種不好的做法。

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

輸出

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM