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 th
This answer is based on the @gommen one.
#!/usr/bin/env python
from itertools import groupby
from operator import itemgetter
L = [
('a', 1),
('a', 2),
('a', 3),
('b', 1),
('b', 2),
('c', 1),
]
key = itemgetter(0)
L.sort(key=key) #NOTE: use `L.sort()` if you'd like second items to be sorted too
for k, group in groupby(L, key=key):
print k, ' '.join(str(item[1]) for item in group)
Output:
a 1 2 3
b 1 2
c 1