尝试计算特定值在Python字典中出现的次数,但似乎无法使其正常工作。在
我的字典是这样设置的:
count = ({'John': 2, 'Sam': 1, 'Brian': 2, 'Brian': 2, 'Brian': 1, 'Sam': 2, 'John': 2, 'Henry': 2, 'Brian': 1})
我要得到结果,这样如果用户输入“Brian”,结果将是:
4
或者,如果用户输入“Sam”,结果将是:
2
number = 0
userInput = input("Please enter a player: ")
for k, v in count.items():
if k == userInput:
number =+ 1
print(number)
有没有更好的方法来做这件事,就像现在输入'Sam'它只会输出'1'? 谢谢!在
因为python字典必须有唯一的键,所以计算一个键出现的次数在这里不起作用。您可以阅读documentation以获取有关此数据结构的更全面的详细信息。在
此外,您可以在字典中存储每个名称的计数:
然后调用每个键以获取计数值:
^{pr2}$您也可以将名称保留为列表,然后调用^{} 来计算名称出现的次数:
它返回一个
Counter()
对象,dict
的子类。在一本字典只能有一次钥匙。 当您创建
count = ({'John': 2, 'Sam': 1, 'Brian': 2, 'Brian': 2, 'Brian': 1, 'Sam': 2, 'John': 2, 'Henry': 2, 'Brian': 1})
时,Python存储{'John': 2, 'Brian': 1, 'Sam': 2, 'Henry': 2}
(值可能会改变,因为对于一个多次出现的键,没有保留什么值的规则)。Cfthe Python documentation for dictionaries所以计数永远是1。在
如果你想多次拥有一个键,不要使用字典,而是使用一组对(大小为2的元组)列表。在
相关问题 更多 >
编程相关推荐