How to split a list of two sets into two lists?

I have a list of 2 tuples. I would like to split the list into two lists, one list consisting of the first elements of all tuples in the list, and the other list consists of the second elements of all tuples. I wonder how to do it effectively? Thanks!

For example, I have a list y :

 >>> y = [('ab',1), ('cd', 2), ('ef', 3) ] >>> type(y) <type 'list'> 

I hope to get two lists ['ab', 'cd', 'ef'] and [1, 2, 3] .

+7
python list
source share
6 answers
 a,b = zip(*y) 

- that’s all you need ...

or if you need them as lists, not tuples

 a,b = map(list,zip(*y)) 
+21
source share

Use zip and list :

 >>> y = [('ab', 1), ('cd', 2), ('ef', 3)] >>> a,b = [list(c) for c in zip(*y)] >>> a ['ab', 'cd', 'ef'] >>> b [1, 2, 3] >>> 
+6
source share

zip with unpacking arguments * will give you tuples:

 >>> a, b = zip(*y) >>> a ('ab', 'cd', 'ef') >>> b (1, 2, 3) 

If you need lists, you can use map :

 >>> a, b = map(list, zip(*y)) >>> a ['ab', 'cd', 'ef'] >>> b [1, 2, 3] 
+6
source share

try the following:

 def get_list(tuples): list1 = [] list2 = [] for i in tuples: list1.append(i[0]) list2.append(i[1]) return list1, list2 y = [('ab',1), ('cd', 2), ('ef', 3) ] letters, numbers = get_list(y) 
+1
source share

One way to do this is to first convert the list to a temp dictionary, then assign the keys and values ​​of the temp dictionary to two lists

 y = [('ab', 1), ('cd', 2), ('ef', 3)] temp_d = dict(y) list1 = temp_d.keys() list2 = temp_d.values() print list1 print list2 
+1
source share
 l1 = [] l2 = [] for i in y: l1.append(i[0]) l2.append(i[1]) 

l1 ['ab', 'cd', 'ef'] l2 [1, 2, 3]

Adding each value to another

0
source share

All Articles