0


Python list题目小记

作为一个刚入手python的萌新记录一下平常工作或者面试中遇到的一写问题和解决思路

题目:已知 a=[1,1,1,2,2,2,2,6,5,5,5,5],将该列表以元素出现个数以多到少排序。

效果: list = [2,5,1,6]

代码:

-- coding: UTF-8 --

a=[1,1,1,2,2,2,2,6,5,5,5,5]
#将列表去重
b = list(set(a))
num = []
#统计每个元素出现的次数,并将次数以降序排列
for i in b:
num.append(a.count(i))
num1 = sorted(num,reverse=True)
#根据元素出现的次数,在新的列表中以出现次数为降序添加元素
num2 =[]
for x in num1:
for y in a:
if x == a.count(y):
num2.append(y)
else:
pass
num3 = []#注:这个列表的元素会非常多且重复
#去重工作,将列表以list = [2,5,1,6]输出
for n in num2:
if n not in num3:
num3.append(n)
print(num3)

标签: python

本文转载自: https://blog.csdn.net/weixin_64081258/article/details/123067503
版权归原作者 Zero萌 所有, 如有侵权,请联系我们删除。

“Python list题目小记”的评论:

还没有评论