python - 给定一个数组打印最不频繁的元素
问题描述
给你一个数字数组。打印最少出现的元素。如果有超过 1 个元素,则按其值的降序打印所有元素。
输入:
[9, 1, 6, 4, 56, 56, 56, 6, 4, 2]
输出:
[9, 2, 1]
我实际上得到了输出,但没有执行私人案例,请帮助我。
from collections import Counter
n=int(input())
ans=""
list1=[]
list2=[]
list1=[int(x) for x in input().strip().split()][:n]
dict1=dict(Counter(list1))
k=min(dict1,key=dict1.get)
l=dict1[k]
for i,j in dict1.items():
if(j==l):
list2.append(i)
list2.reverse()
for i in list2:
ans+=str(i)+' '
print(ans[:-1])
解决方案
我看到很多复杂的答案。它实际上可以通过对实例中的项目使用列表理解来完成Counter()
:
>>> from collections import Counter
>>> count = Counter([9, 1, 6, 4, 56, 56, 56, 6, 4, 2])
>>> values = [key for key, value in count.items() if value == min(count.values())]
>>> values.sort(reverse=True) # [9, 2, 1]
推荐阅读
- c - C - 数据存储/访问
- rest - 如何同时处理多个 PUT 和 PATCH 请求
- mysql - 使用 docker-compose 时更改 mysql 日志记录级别
- python - 绘制y轴对x轴的导数python pandas
- android - 有没有通过我的应用程序发送短信的免费方式?
- ios - 处理低内存设备中文件(json)的持久性并将它们发送到服务器
- kernel - 内核在使用 fbprophet 拟合模型后死亡
- java - 堆栈跟踪中包含 Lombok 构建器的异常
- c++ - c++ 。我试图通过在开关内使用数组来获取用户输入,但是当我运行代码时它显示分段错误?
- python - 使用路由器为 ModelViewSet 的检索方法创建自定义或修改的 url