Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make two lists out of two-elements tuples that are stored in a list of lists of tuples

Tags:

python

list

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)
like image 378
Vesper Avatar asked Jun 29 '20 15:06

Vesper


People also ask

How do you split a tuple into two lists?

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.


1 Answers

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]
like image 134
yatu Avatar answered Oct 20 '22 12:10

yatu