在Python字典中计算特定值

2024-09-26 22:53:43 发布

您现在位置:Python中文网/ 问答频道 /正文

尝试计算特定值在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'? 谢谢!在


Tags: 用户numberforinput字典samcountjohn
2条回答

因为python字典必须有唯一的键,所以计算一个键出现的次数在这里不起作用。您可以阅读documentation以获取有关此数据结构的更全面的详细信息。在

此外,您可以在字典中存储每个名称的计数:

counts = {'Brian': 4, 'John': 2, 'Sam': 2, 'Henry': 1}

然后调用每个键以获取计数值:

^{pr2}$

您也可以将名称保留为列表,然后调用^{}来计算名称出现的次数:

>>> from collections import Counter
>>> names = ['John', 'Sam', 'Brian', 'Brian', 'Brian', 'Sam', 'John', 'Henry', 'Brian']
>>> Counter(names)
Counter({'Brian': 4, 'John': 2, 'Sam': 2, 'Henry': 1})

它返回一个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的元组)列表。在

相关问题 更多 >

    热门问题