user1995519
user1995519

Reputation: 107

combine tuples to form lists

data= [('a ', 1), ('b ', 3), ('a ', 4), ('b', 2),]

How do get two lists with the first element of tuple as the list name and the second as values?

a= [1,4]
b= [3,2]

Upvotes: 1

Views: 183

Answers (4)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250891

You should use dictionary here, instead of creating multiple variables.

In [14]: data= [('a ', 1), ('b ', 3), ('a ', 4), ('b',2),]

In [15]: dic={}

In [16]: for k,v in data:
   ....:     dic.setdefault(k.strip(),[]).append(v)
   ....:     

In [18]: dic
Out[18]: {'a': [1, 4], 'b': [3, 2]}

Upvotes: 0

Jakub M.
Jakub M.

Reputation: 33827

Lev's answer is what you look for. Additionally, ou can group by an arbitrary key:

grouped = defaultdict(list)
[grouped[key].append(value) for key, value in data]    

By the way, defaultdict is one of many built-in types worth examining. There are many types and functions that may solve your daily problems. Check at least operator, itertools and functools modules.

Upvotes: 0

DSM
DSM

Reputation: 353019

As explained in your previous question, you shouldn't try to change the name you're binding something to. [The left-hand side of something = 3, I mean.] It causes nothing but trouble. You could use a dict instead, and a defaultdict would make things handy:

>>> data= [('a ', 1), ('b ', 3), ('a ', 4), ('b', 2),]
>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> for k, v in data:
...     d[k.strip()].append(v)
...     
>>> d
defaultdict(<type 'list'>, {'a': [1, 4], 'b': [3, 2]})

After which

>>> d['a']
[1, 4]
>>> d['b']
[3, 2]

would work.

Upvotes: 6

Lev Levitsky
Lev Levitsky

Reputation: 65791

As some of the keys in your example have some extra whitespace, I'm using strip:

In [11]: [x[1] for x in data if x[0].strip() == 'a']
Out[11]: [1, 4]

In [12]: [x[1] for x in data if x[0].strip() == 'b']
Out[12]: [3, 2]

Upvotes: 1

Related Questions