我对把字典算在单子上一点想法都没有。就像实例列表一样
我们有这样的名单
list_of_dict = [{'teamA': 'Ocean Gaming ', 'teamB': 'PSISTORM Gaming', 'score1': '0', 'score2': '1'},
{'teamA': 'Ocean Gaming ', 'teamB': 'PSISTORM Gaming', 'score1': '0', 'score2': '1'},
{'teamA': 'Ocean Gaming ', 'teamB': 'PSISTORM Gaming', 'score1': '1', 'score2': '0'},
{'teamA': 'Jin Air Green Wings ', 'teamB': 'Invictus Gaming', 'score1': '1', 'score2': '0'},
{'teamA': 'Jin Air Green Wings ', 'teamB': 'Invictus Gaming', 'score1': '1', 'score2': '0'},
{'teamA': 'Jin Air Green Wings ', 'teamB': 'Invictus Gaming', 'score1': '1', 'score2': '0'}]我希望在像下面的列表那样计算输出之后
list_of_dict = [
{'teamA': 'Ocean Gaming ', 'teamB': 'PSISTORM Gaming', 'score1': '1', 'score2': '2'}
{'teamA': 'Jin Air Green Wings ', 'teamB': 'Invictus Gaming', 'score1': '3', 'score2': '0'}
]发布于 2019-05-14 11:41:21
@umn 's answer更优雅,而且可能更优化,因此如果您可以在脚本中使用numpy,则更倾向于这样做。下面是一种不需要额外库就可以这样做的简单方法:
list_of_dict = [{'teamA': 'Ocean Gaming ', 'teamB': 'PSISTORM Gaming', 'score1': '0', 'score2': '1'},
{'teamA': 'Ocean Gaming ', 'teamB': 'PSISTORM Gaming', 'score1': '0', 'score2': '1'},
{'teamA': 'Ocean Gaming ', 'teamB': 'PSISTORM Gaming', 'score1': '1', 'score2': '0'},
{'teamA': 'Jin Air Green Wings ', 'teamB': 'Invictus Gaming', 'score1': '1', 'score2': '0'},
{'teamA': 'Jin Air Green Wings ', 'teamB': 'Invictus Gaming', 'score1': '1', 'score2': '0'},
{'teamA': 'Jin Air Green Wings ', 'teamB': 'Invictus Gaming', 'score1': '1', 'score2': '0'}]
intermediate_dict = {}
for d in list_of_dict:
key = (d['teamA'], d['teamB'])
if key in intermediate_dict.keys():
intermediate_dict[key][0] += int(d['score1'])
intermediate_dict[key][1] += int(d['score2'])
else:
intermediate_dict[key] = [int(d['score1']), int(d['score2'])]
final_list = []
for k,v in intermediate_dict.items():
temp_dict = {}
temp_dict['teamA'] = k[0]
temp_dict['teamB'] = k[1]
temp_dict['score1'] = v[0]
temp_dict['score2'] = v[1]
final_list.append(temp_dict)
print(final_list)https://stackoverflow.com/questions/56129085
复制相似问题