python3:如何找到字典中出现最多的值?

2024-05-20 18:21:03 发布

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

我想做一个程序,当给我这样的口述时-

    sports_played={sam:baseball,john:tennis,dan:tennis,joe:cricket,drew:tennis,mark:baseball}

还应该是网球,也就是说网球是世界上最受欢迎的运动,也就是说网球是世界上出现次数最多的运动

如果问题出了问题,请提前道歉。这是我的第一个问题。你知道吗


Tags: 程序sam世界johnmarkjoedansports
3条回答

如果您查看dir(dict),您将看到一个有趣的方法,可以在dict class/object中使用,即dict.get()。你知道吗

因此,如果在python解释器中键入help(dict.get),您将得到:

Help on method_descriptor:

get(...) D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.

因此,基本上dict.get()将查看dict中是否存在键,并将其设置为d值(默认值为None)。你知道吗

所以,我们可以这样做:

eaters = {'chicken': 5, 'meat': 5, 'rice': 3}

counts = {}
for k in eaters.values():
    # If we find the k key in counts we add 1
    # If not set the count to 1
    counts[k] = counts.get(k, 0) + 1

print(counts)

>>> {3: 1, 5: 2}

所以,我们有一个dict,在这个dict中,我们计算食客dict的每个值出现了多少次

最后,要获得eatersdict值的最大出现次数,我们可以执行以下操作:

# get_max: temporar variable in which we stock the max
# val = will stock the key with the max value in counts dict
get_max, val = 0, 0
for k, v in counts.items():
    if v > get_max:
        get_max = v
        val = k
print(k)

>>> 5

如果要获取最大元素的key,即meat,可以使用以下代码:

>>> list(eaters.keys())[list(eaters.values()).index(max(eaters.values()))]
>>> 'meat'

如果我们假设eaters是一本字典,那么:

eaters={'chicken':5,'meat':7,'rice':3} 
max(eaters.values())

结果: 七

在现实世界中,您不会使用循环来实现这一点。你知道吗

查看eaters中的可用内容

dir(eaters)
['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values', 'viewitems', 'viewkeys', 'viewvalues']

eaters.keys()
['chicken', 'rice', 'meat']
eaters.values()
[5, 3, 7]

等等

循环版本:

x=0
for i in eaters.values():
    if i > x:
        x = i
print i
7

相关问题 更多 >