python-3.x - 如何仅访问字典中的特定键?
问题描述
我正在解决 Hackerrank 上的一个问题,我正在使用字典:
dic = {'1':type1, '2':type2, '3':type3, '4',type4, '5',type5}
在我的问题中,我需要返回具有最大值的键(类型变量是每种类型的计数)。就像如果值为type4
3(type4 计数为 3)那么我需要返回 key '4'
。我怎么做?
我尝试使用keys()
和items()
函数,但它们返回列表而不是特定元素。
type1 = 0
type2 = 0
type3 = 0
type4 = 0
type5 = 0
maxim = 0
for i in arr:
if i == 1:
type1+=1
elif i == 2:
type2+=1
elif i == 3:
type3+=1
elif i == 4:
type4+=1
else:
type5+=1
dic = {'1':type1, '2':type2, '3':type3, '4':type4, '5':type5}
for j in range(1,len(dic)):
if dic[str(j)]>maxim:
maxim = dic[str(j)]
return maxim
我的输出结果是 3,这是其中一个类型变量持有的最大计数,但我需要的是让它将键返回到相应的值(这里值是 3,键是 4)。
解决方案
您清理的代码将导致:
arr = [1,2,3,2,3,4,5,3,4,21,1,2,3,2,3,4,5,6,5,4,3,2,3,4,1,1,1,2]
dic = {}
for i in arr:
dic.setdefault(i,0) # set count of 0 if not existent
dic[i] +=1 # increase count
# use the builtin max function to get the item with the highest count
m = max(dic.items(), key = lambda x:x[1])
print(m) # (3,7)
使用 acollections.Counter
会加快速度,它是一个专门计算事物的字典:
from collections import Counter
arr = [1,2,3,2,3,4,5,3,4,21,1,2,3,2,3,4,5,6,5,4,3,2,3,4,1,1,1,2]
# feed the array into Counter (which is a specialized counting dictionary)
c = Counter( arr )
print(c.most_common())
key, occ = c.most_common()[0]
print( key,"occured",occ,"times")
输出:
# counter.most_common() - i.e. 3 occured 7 time, 2 occured 6 times etc. it is sorted
[(3, 7), (2, 6), (1, 5), (4, 5), (5, 3), (6, 1), (21, 1)]
3 occured 7 times
推荐阅读
- javascript - 如何使用 NodeJS 和 Yahoo! 发出 POST 请求 梦幻体育API
- c++ - ',' 标记之前应为 ')' - SFML 创建 RectangleShape
- python - 使用 N 个工作人员执行多处理任务列表的最佳方法?
- algorithm - 水壶问题GCD解决方法解释
- javascript - Puppeteer 无法在特定的输入字段中写入
- java - 在 JMH 中的每个基准测试之后恢复 Java 列表状态
- react-native - ReactNative:使用 Axios 将图像文件上传到服务器不起作用
- c++ - macosx 上信号处理程序中的 rip 寄存器值
- python - shap.KernelExplainer,为背景中有许多零的图像更改“mask_image”函数
- c - 我可以发布使用补丁的 crate 吗?