我們需要對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