python实现 列表内元素按照出现次数排序

我们需要对List进行排序,Python提供了两个方法
对给定的List L进行排序,
方法1.用List的成员函数sort进行排序
方法2.用内建函数sorted进行排序(从python 2.4开始)

sort函数定义:sort(cmp=None, key=None, reverse=False)

sorted函数定义:sorted(iterable, cmp=None, key=None, reverse=False)

lst = []

from collections import Counter
l = ['fa|aaaa|fsjkedf|\n', 'sdaffs|asdffdsa|0|0|||a1|a1|a1|\n']
for i in l:
    lst.extend(i.strip('\n').split('|'))
    # print(ls)
d2 = Counter(lst)
# print(d2.items())
sorted_x = sorted(d2.items(), key=lambda x: x[1],reverse=True) #key:按照元组的第二个元素排序;reverse:升降排序
print(sorted_x)
for i in sorted_x:
    print(i[0],i[1])

from collections import Counter
d = [ ('1.2', 'a/c',),('1.3', 'a/c',),('1.3', 'a/c',),('1.1', 'a/b',)]
print(Counter(d,)) #Counter({('1.3', 'a/c'): 2, ('1.2', 'a/c'): 1, ('1.1', 'a/b'): 1})

Python排序函数sort()和sorted()详解 可参考
https://blog.csdn.net/lyy14011305/article/details/76148512?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param

posted @ 2020-11-13 10:41  hanfe1  阅读(1931)  评论(0编辑  收藏  举报