Python练习元组、集合和列表

Python Exercise Tuples, set and list

你能帮帮我吗?我尝试了一切,但我迷路了。 从数据中我需要得到这个元组列表。 这个想法是以最易读的方式组织这个列表。 从数据中,如果我找到一个 1,我需要用该值创建一个元组,并用第二列的字母创建一个列表,这样它就会按顺序出现,比如 ['E'、'B' , 'E'].

这是数据:

[(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'])

您可以使用 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)

输出:

[('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 '])]

或者,如果您先验知道密钥,则可以提前设置密钥。这不需要 defaultdict 也不需要 sorted(后者在 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())