Home > front end >  Python Exercise Tuples, set and list
Python Exercise Tuples, set and list

Time:11-07

can you please help me? I tried everything, but I'm lost. From the data I need to get this list of tuples. The idea is to organize this list in the best readable way. From the data, if I found a 1, I need to make a tuple with the value and a list with the letters from the second column, so It would appear in order, like ['E', 'B', 'E'].

This is the data:

[(1, 'E'),
 (2, 'A'),
 (5, 'B'),
 (3, 'A'),
 (6, 'C'),
 (7, 'A'),
 (9, 'A'),
 (1, 'B'),
 (2, 'E'),
 (3, 'B'),
 (7, 'C'),
 (5, 'C'),
 (3, 'D'),
 (8, 'E'),
 (9, 'B'),
 (8, 'D'),
 (3, 'E'),
 (5, 'D'),
 (8, 'E'),
 (9, 'E'),
 (7, 'E'),
 (3, 'E'),
 (5, 'D'),
 (9, 'A'),
 (4, 'E'),
 (6, 'E'),
 (8, 'A'),
 (5, 'E'),
 (6, 'A'),
 (0, 'C'),
 (9, 'A'),
 (3, 'D'),
 (5, 'E'),
 (4, 'B'),
 (6, 'B'),
 (7, 'D'),
 (8, 'B'),
 (9, 'C'),
 (1, 'E'),
 (5, 'E')]

# Result/
# ('0', ['C'])
# ('1', ['E', 'B', 'E'])
# ('2', ['A', 'E'])
# ('3', ['A', 'B', 'D', 'E', 'E', 'D'])
# ('4', ['E', 'B'])
# ('5', ['B', 'C', 'D', 'D', 'E', 'E', 'E'])
# ('6', ['C', 'E', 'A', 'B'])
# ('7', ['A', 'C', 'E', 'D'])
# ('8', ['E', 'D', 'E', 'A', 'B'])
# ('9', ['A', 'B', 'E', 'A', 'A', 'C'])

CodePudding user response:

You can use defaultdict:

from collections import defaultdict
data = [(1, 'E'), (2, 'A'), (5, 'B'), (3, 'A'), (6, 'C'), (7, 'A'), (9, 'A'), (1, 'B'),
        (2, 'E'), (3, 'B'), (7, 'C'), (5, 'C'), (3, 'D'), (8, 'E'), (9, 'B'), (8, 'D'),
        (3, 'E'), (5, 'D'), (8, 'E'), (9, 'E'), (7, 'E'), (3, 'E'), (5, 'D'), (9, 'A'),
        (4, 'E'), (6, 'E'), (8, 'A'), (5, 'E'), (6, 'A'), (0, 'C'), (9, 'A'), (3, 'D'),
        (5, 'E'), (4, 'B'), (6, 'B'), (7, 'D'), (8, 'B'), (9, 'C'), (1, 'E'), (5, 'E')]

d = defaultdict(list)
for x, y in data:
    d[str(x)].append(y)

output = sorted(d.items())
print(output)

Output:

[('0', ['C']), ('1', ['E', 'B', 'E']), ('2', ['A', 'E']), ('3', ['A', 'B', 'D', 'E', 'E', 'D']), ('4', ['E', 'B']), ('5', ['B', 'C', 'D', 'D', 'E', 'E', 'E']), ('6', ['C', 'E', 'A', 'B']), ('7', ['A', 'C', 'E', 'D']), ('8', ['E', 'D', 'E', 'A', 'B']), ('9', ['A', 'B', 'E', 'A', 'A', 'C '])]

Alternatively, if you know the keys a priori, you can set the keys in advance. This won't need defaultdict nor sorted (the latter in python 3.7 ).

d = {str(k): [] for k in range(10)}
for x, y in data:
    d[str(x)].append(y)
output = list(d.items())
  • Related