首页 > 解决方案 > 给定一个数组打印最不频繁的元素

问题描述

给你一个数字数组。打印最少出现的元素。如果有超过 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])

标签: python

解决方案


我看到很多复杂的答案。它实际上可以通过对实例中的项目使用列表理解来完成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]

推荐阅读