I have a list which contains many lists and in those there 4 tuples.
my_list = [[(12, 1), (10, 3), (4, 0), (2, 0)],
[(110, 1), (34, 2), (12, 1), (55, 3)]]
I want them in two separate lists like:
my_list2 = [12,10,4,2,110,34,12,55]
my_list3 = [1,3,0,0,1,2,1,3]
my attempt was using the map
function for this.
my_list2 , my_list3 = map(list, zip(*my_list))
but this is giving me an error:
ValueError: too many values to unpack (expected 2)
To convert a list of tuples to two lists: Use the zip() function with the * operator to unzip the list. Use the map() function to convert the tuples in the zip object to lists. Use the list() class to convert the map object to a list.
Your approach is quite close, but you need to flatten first:
from itertools import chain
my_list = [[(12, 1), (10, 3), (4, 0), (2, 0)], [(110, 1), (34, 2), (12, 1), (55, 3)]]
my_list2 , my_list3 = map(list,zip(*chain.from_iterable(my_list)))
my_list2
# [12, 10, 4, 2, 110, 34, 12, 55]
my_list3
# [1, 3, 0, 0, 1, 2, 1, 3]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With