所以我得到了下面的代码,我想做的是获取输入元组的每一个秒值,并将其保存到字典中作为dict.key
,并将dict.value
首先设置为0。之后,我想检查保存的字典,每次这个dict.key
出现在元组中,我想把它的计数放在dict.value
中。代码当前给我一个错误。
def movie_awards(results):
"""
I want to ignore every first value of the tuple
"""
results = list(results)
answer = {x[1]:0 for x in results}
for x in results:
answer[x[1]] = answer[x] + 1
print(answer)
result = {("Best Picture", "Parasite"),
("Best Actor", "Joker"),
("Best Actress", "Judy"),
("Best Sound Editing", "Ford v Ferrari"),
("Best Sound Editing", "1917"),
("Best Original Score", "Joker"),
("Best Costume Design", "Little Women"),
("Best Visual Effects", "Little Women"),
("Best Director", "Parasite")}
使用+=
:
for x in results:
answer[x[1]] += 1
print(answer)
做:
answer[x]
python正在尝试获取密钥为('Best Original Score', 'Joker')
的key:value
对。因为它不存在,所以会引发一个键错误。
您也可以直接使用collections.Counter
:
from collections import Counter
def movie_awards(results):
return Counter(x[1] for x in results)
你可以使用Counter:
from collections import Counter
c = Counter([t[1] for t in result])
>>> Counter({'Joker': 2, 'Parasite': 2, 'Little Women': 2, '1917': 1, 'Ford v Ferrari': 1, 'Judy': 1})