简体   繁体   English

计算 Python 字典中的特定值

[英]Counting specific values within Python Dictionary

Trying to count the amount of times a specific value occurs within a Python dictionary but can't seem to get it to work.试图计算特定值出现在 Python 字典中的次数,但似乎无法让它工作。

My dictionary is set up as so:我的字典是这样设置的:

count = ({'John': 2, 'Sam': 1, 'Brian': 2, 'Brian': 2, 'Brian': 1, 'Sam': 2, 'John': 2, 'Henry': 2, 'Brian': 1}) count = ({'John': 2, 'Sam': 1, 'Brian': 2, 'Brian': 2, 'Brian': 1, 'Sam': 2, 'John': 2, 'Henry': 2,'布赖恩':1})

I am to get the result so that if a user inputs 'Brian' the result would be:我要得到结果,如果用户输入“Brian”,结果将是:

4 4

Or if the user were to enter 'Sam' the result would then be:或者,如果用户输入“Sam”,结果将是:

2 2

number = 0
userInput = input("Please enter a player:  ")
for k, v in count.items():
        if k == userInput:
            number =+ 1
print(number)

Is there a better way of doing this, as currently if were to type in 'Sam' it would only output '1'?有没有更好的方法来做到这一点,因为目前如果输入“山姆”,它只会输出“1”? Thanks !谢谢 !

A dictionary can have a key only once.字典只能有一个键。 When you create count = ({'John': 2, 'Sam': 1, 'Brian': 2, 'Brian': 2, 'Brian': 1, 'Sam': 2, 'John': 2, 'Henry': 2, 'Brian': 1}) , Python stores {'John': 2, 'Brian': 1, 'Sam': 2, 'Henry': 2} (values can change as there is no rule on what value to keep for a key which appears more than once).当你创建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} (值可以改变,因为没有规则为多次出现的键保留什么值)。 Cf the Python documentation for dictionaries参见字典的 Python 文档

So the count will always be 1.因此计数将始终为 1。

If you want to have a key multiple times, don't use a dictionary but a list of pairs (tuples of size 2).如果您想多次使用一个键,请不要使用字典,而是使用对列表(大小为 2 的元组)。

Since python dictionaries must have unique keys, counting how many times a key occurs wont work here.由于 python 字典必须有唯一的键,所以计算一个键出现的次数在这里不起作用。 You can read the documentation for more comprehensive details about this data structure.您可以阅读文档以获取有关此数据结构的更全面的详细信息。

Furthermore, You can store counts for each name in a dictionary:此外,您可以在字典中存储每个名称的计数:

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

Then call each key to obtain the count value:然后调用每个键获取计数值:

>>> counts['Brian']
4
>>> counts['Sam']
2

You could also just keep the names as a list, and call collections.Counter to count how many times a name occurs:您也可以将名称保留为列表,并调用collections.Counter来计算名称出现的次数:

>>> 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})

Which returns a Counter() object, a subclass of dict .它返回一个Counter()对象,它是dict的子类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM