首页 > 解决方案 > 如何计算列表中的选票并将其存储在字典中以跟踪选票数量

问题描述

例子:

list = ["a voted b", "c voted b", "d voted e", "e voted skip", "something else"]

字典结果:

{"b":2, "e":1, "skip":1}

标签: pythonlistdictionary

解决方案


from collections import defaultdict

mylist = ["a voted b", "c voted b", "d voted e", "e voted skip"]

votes = defaultdict(int)
for item in mylist:
    votes[item.split()[-1]] += 1

推荐阅读