python实现:重复列表按重复次数排序
2021-03-28 21:25
标签:bcd range 方法 append result sorted aac end adb python实现:重复列表按重复次数排序 标签:bcd range 方法 append result sorted aac end adb 原文地址:https://www.cnblogs.com/Runa/p/13624222.html#重复列表按重复次数排序方法1
s = ‘aacbddbcdadb‘
lists1=list(s)
uniques1 = set(lists1)
dict_str = {}
for unique1 in uniques1:
i=0
for list1 in lists1:
if list1 == unique1:
i += 1
dict_str[unique1]=i
print(dict_str)
list2=[]
while dict_str:
max_count = max(dict_str.values())
for key,value in dict_str.items():
if value == max_count:
for i in range(0,value):
list2.append(key)
break
del dict_str[key]
print("after del dict_str-"+str(dict_str))
print(list2)
#重复列表按重复次数排序方法2
s = ‘aacbddbcdadb‘
lists = list(s)
uniquelist = set(lists)
dict={}
result_list = []
for unique in uniquelist:
dict[unique] = lists.count(unique)
print(dict)
while dict:
max_count = max(dict.values())
for key,value in dict.items():
if value == max_count:
for i in range(1,value+1):
result_list.append(key)
break
del dict[key]
print(result_list)
#重复列表按重复次数排序方法3 ------------这个方案比较好,对字典按照value进行了倒序排列,使用到了lambda匿名函数。
s = ‘aacbddbcdadb‘
lists = list(s)
uniquelist = set(lists)
dict={}
ordered_dict={}
result_list = []
for unique in uniquelist:
dict[unique] = lists.count(unique)
print(dict)
ordered_dict = sorted(dict.items(),key=lambda x:x[1],reverse=True) ##对字典按照value进行倒序排序,使用了匿名函数lambda
print(ordered_dict)
for key,value in ordered_dict:
for i in range(1,value+1):
result_list.append(key)
print(result_list)
# ordered_dict = sorted(dict.items(),key=lambda x:x[1],reverse=True)
文章标题:python实现:重复列表按重复次数排序
文章链接:http://soscw.com/index.php/essay/69216.html