from collections import defaultdict
#第一种写法
s = [('yellow',1),('blue',2),('yellow',3),('blue',4),('red',5)]
d=defaultdict(list)
for k,v in s: d[k].append(v)
print(d.items()) #dict_items([('yellow', [1, 3]), ('blue', [2, 4]), ('red', [5])])
print(list(d.items())) #[('yellow', [1, 3]), ('blue', [2, 4]), ('red', [5])]
#第二种写法
s = [('yellow',1),('blue',2),('yellow',3),('blue',4),('red',5)]
d = defaultdict(list)
for k,v in s:
d[k].append(v)
print(d)
#执行结果: dict_items([('yellow', [1, 3]), ('blue', [2, 4]), ('red', [5])])
print(dict(d)) #{'yellow': [1, 3], 'blue': [2, 4], 'red': [5]}
print(list(d)) #['yellow', 'blue', 'red']