[英]Zipping together entries of a list of lists using Python
If I have a list with multiple lists (for simplicity 3, but I actually have a very large amount): 如果我有一个包含多个列表的列表(为简单起见3,但实际上数量很多):
list = [[1,a,2],[3,b,4],[5,c,6]]
How do I obtain a new lists of lists that combines the original list items based on their positions using Python? 如何使用Python根据列表的位置获取将原始列表项组合在一起的新列表列表?
new_list = [[1,3,5],[a,b,c],[2,4,6]]
I've been trying the zip function on "list" but it's not working, what am I doing wrong? 我一直在尝试“列表”上的zip功能,但是它不起作用,我在做什么错?
This does what you want. 这就是您想要的。
mylist = [[1,"a",2],[3,"b",4],[5,"c",6]]
mylist2 = list(map(list, zip(*mylist)))
Please don't use list, or any other built-in as variable name. 请不要使用列表或任何其他内置变量名称。
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.
You can use zip: 您可以使用zip:
a = 1
b = 2
c = 3
l = [[1,a,2],[3,b,4],[5,c,6]]
new_l = list(map(list, zip(*l)))
Output: 输出:
[[1, 3, 5], [1, 2, 3], [2, 4, 6]]
Notice that the variables are now displayed in the second element of new_l
注意,变量现在显示在
new_l
的第二个元素中
You can use zip , also keep in minde it's bad practice to use built-in functions as variable name. 您可以使用zip ,也请记住,将内置函数用作变量名是一种不好的做法。
l = [[1,a,2],[3,b,4],[5,c,6]]
list(zip(*l))
output 输出
[[1,3,5],[a,b,c],[2,4,6]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.