I’m still new to Python. I have similar list to the below list:
items = [[4, 'A'], [4, 'B'], [5, 'C'], [5, 'D'], [5, 'E'], [6, 'F'], [6, 'G']]
I’m trying to print it by grouping the first item together and get something like this:
JavaScript
x
4
1
4 : ['A', 'B']
2
5 : ['C', 'D', 'E']
3
6 : ['F', 'G']
4
How do I do this?
Advertisement
Answer
You can use itertools.groupby
and operator.itemgetter
:
JavaScript
1
10
10
1
>>> from itertools import groupby
2
>>> from operator import itemgetter
3
>>> list_ = [[4, 'A'], [4, 'B'], [5, 'C'], [5, 'D'], [5, 'E'], [6, 'F'], [6, 'G']]
4
>>> print(*(f'{k}: {sum(list(g), [])}'
5
for k, g in groupby(list_, key=lambda x: list.pop(x, 0))),
6
sep='n')
7
4: ['A', 'B']
8
5: ['C', 'D', 'E']
9
6: ['F', 'G']
10
If you want to do this without importing anything:
JavaScript
1
18
18
1
>>> list_ = [[4, 'A'], [4, 'B'], [5, 'C'], [5, 'D'], [5, 'E'], [6, 'F'], [6, 'G']]
2
3
>>> table = {}
4
5
>>> for key, value in list_:
6
table.setdefault(key, []).append(value)
7
8
9
>>> table
10
{4: ['A', 'B'], 5: ['C', 'D', 'E'], 6: ['F', 'G']}
11
12
>>> for key, group in table.items():
13
print(f'{key}: {group}')
14
15
4: ['A', 'B']
16
5: ['C', 'D', 'E']
17
6: ['F', 'G']
18