示例:
list = ["a voted b", "c voted b", "d voted e", "e voted skip", "something else"]
字典结果:
{"b":2, "e":1, "skip":1}
发布于 2020-11-16 19:39:49
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
发布于 2020-11-16 19:39:10
如果投票总是有相同的x voted y
结构,你可以这样做:
# get a defaultdict for storing the result
from collections import defaultdict
result = defaultdict(int)
# split out the voted from each string in the list
pairs = [i.split(' voted ') for i in list]
# for each pair, increase the value for that key in the defaultdict by 1
for _, vote in pairs:
result[vote] += 1
# convert back to dict
result = dict(result)
发布于 2020-11-16 19:44:43
one liner怎么样:
from collections import Counter
result = dict(Counter([s.split(' voted ')[-1] for s in list]))
https://stackoverflow.com/questions/64864533
复制