I have a list of tuples like this:
[
('a', 1),
('a', 2),
('a', 3),
('b', 1),
('b', 2),
('c', 1),
]
I want to iterate through this keying by the first item, so for example I could print something like this:
a 1 2 3
b 1 2
c 1
How would I go about doing this without keeping an item to track whether the first item is the same as I loop round the tuples? This feels rather messy (plus I have to sort the list to start with)...
I would just do the basic
If it's this short, why use anything complicated. Of course if you don't mind using setdefault that's okay too.
A solution using groupby
groupby(l, lambda x:x[0]) gives you an iterator that contains ['a', [('a', 1), ...], c, [('c', 1)], ...]
produces:
Print list of tuples grouping by the first item
This answer is based on the @gommen one.
Output:
Slightly simpler...