输入:
x = ( (1,"A", 10),(1,"B", 10),(1,"B", 10),(1,"C", 10),(1,"C", 10),(1,"B", 10),(1,"A", 10),(1,"A", 10),(1,"C", 10),(1,"B", 10))
预期产出:
{'A': [(1, 'A', 10), (7, 'A', 70), (8, 'A', 80)], 'B': [(2, 'B', 20), (3, 'B', 30), (6, 'B', 60), (10, 'B', 100)], 'C': [(4, 'C', 40), (5, 'C', 50), (9, 'C', 90)]}
基本上按元组中的元素之一对我的元组进行分组
我试过这个,但不觉得pythonic
def consolidate(values):
res = {}
for a in values:
if a[1] in res:
p = res[a[1]]
p.append(a)
res[a[1]] = p
else:
res[a[1]] = [a]
return res
您可以使用
dict.setdefault
:
out = {}
for a, b, c in x:
out.setdefault(b, []).append((a, b, c))
print(out)
印花:
{
"A": [(1, "A", 10), (1, "A", 10), (1, "A", 10)],
"B": [(1, "B", 10), (1, "B", 10), (1, "B", 10), (1, "B", 10)],
"C": [(1, "C", 10), (1, "C", 10), (1, "C", 10)],
}