给定一个数组打印最不频繁的元素

时间:2019-10-09 12:30:49

标签: 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])

4 个答案:

答案 0 :(得分: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]

答案 1 :(得分:0)

出现错误的原因是因为Counter / Dictionary是无序集合。因此,每次运行list2时,其元素的顺序都可能不同。尝试为[9、1、6、4、56、6、4、2]输入运行代码。

from collections import Counter
n=int(input())

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.sort(reverse=True)    
print(' '.join(str(i) for i in list2))

答案 2 :(得分:0)

您可以通过在反转列表之前对列表进行简单排序来做到这一点。并且您无需为list创建字符串。只需* list_name,它将使用空格打印列表。

from collections import Counter

n=int(input())
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.sort(reverse=True)

print(*list2)

答案 3 :(得分:0)

没有任何导入,您也可以尝试

def getAllindex(lst, elem):
     return list(filter(lambda a: lst[a] == elem, range(0,len(lst))))

lst = [9, 1, 6, 4, 56, 56, 56, 6, 4, 2]

list_count = [lst.count(xx) for xx in lst]
idx = getAllindex(list_count, min(list_count))

l = list(set([lst[ii] for ii in idx]))
l.sort(reverse = True)
print(l)

输出

[9, 2, 1]