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
如果您查看
dir(dict)
,您将看到一个有趣的方法,可以在dict class/object
中使用,即dict.get()
。你知道吗因此,如果在python解释器中键入
help(dict.get)
,您将得到:因此,基本上
dict.get()
将查看dict中是否存在键,并将其设置为d
值(默认值为None
)。你知道吗所以,我们可以这样做:
所以,我们有一个dict,在这个dict中,我们计算食客dict的每个值出现了多少次
最后,要获得
eaters
dict值的最大出现次数,我们可以执行以下操作:如果要获取最大元素的
key
,即meat
,可以使用以下代码:如果我们假设
eaters
是一本字典,那么:结果: 七
在现实世界中,您不会使用循环来实现这一点。你知道吗
查看
eaters
中的可用内容等等
循环版本:
相关问题 更多 >
编程相关推荐