# 设定给出的非空数组为list_a,如下list_a = [8,1,3,5,1,2,45,8,5,7,7,8,8,8,8,8,8,5,5] # 将list_a去重,留下唯一值list_a_set = set(list_a) # 将list_a去重后的值作为字典的key放到字典中list_a_dict = {x:None for x in list_a_set} # 遍历将list_a去重后的唯一值,统计唯一值出现的次数。把次数作为字典的value放到字典中for l in list_a_set: list_a_dict[l] = list_a.count(l) # 对字典按照value排序,也就是说是将题目中重复次数由多到少进行排序。排序后的类型是个由key值组成的列表listlist_a_max = sorted(list_a_dict, key=list_a_dict.get, reverse=True ) # 对由key值组成的列表list进行切片,前N个数字(将N替换3即可实现)print(list_a_max[0:3]) # N 替换 3
原文地址:https://www.cnblogs.com/jianjiacangcang/p/10585661.html
时间: 2024-11-08 10:04:18