If I have a list with multiple lists (for simplicity 3, but I actually have a very large amount):
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?
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?
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:
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
You can use zip , also keep in minde it's bad practice to use built-in functions as variable name.
l = [[1,a,2],[3,b,4],[5,c,6]]
list(zip(*l))
output
[[1,3,5],[a,b,c],[2,4,6]]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.