sorted 排序方法主要是用在 list 和 dict 中。
sorted 介紹:
其中, iterable 是可迭代類型
cmp 是用於比較的函數,比較什麼由key 決定
key 是列表元素的某個屬性或函數進行作爲關鍵字,有默認值,迭代集合中的一項
reverse 是排序規則,reverse = True 表示降序, reverse= False 表示升序,有默認值
返回值 是一個經過排序的可迭代類型,與iterable 一樣
栗子:
(1)對由tuple 組成的List 排序
Python 代碼
students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10),]
(2)用key 函數排序:返回由tuple 組成的 list
Python 代碼
sorted(students, key=lambda student : student[2]) # sort by age
result = [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
(3)用cmp 函數排序
Python 代碼
sorted(students, cmp=lambda x,y : cmp(x[2], y[2])) # sort by age
result = [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
(4)對字典排序, 返回由tuple 組成的List 不再是字典
Python 代碼
d = {'data1':3, 'data2':1, 'data3':2, 'data4':4}
sorted(d.iteritems(), key=itemgetter(1), reverse=True)
result = [('data4', 4), ('data1', 3), ('data3', 2), ('data2', 1)]
(5)簡單排序栗子:
Python 代碼:
#coding:utf-8
input = [[180, 18, 3], [58, 103, 48, 340], [17, 240], [22, 24, 25, 33, 44], [100]]
def seq_sorted(seq):
sort_index = sorted(range(len(seq)), key=lambda x: len(seq[x]))
return sort_index
sort_index = seq_sorted(input)
# print sort_index
out_sentences = [input[i] for i in sort_index]
print out_sentences
執行後可以得到的結果:
/usr/bin/python2.7 /home/yongcai/PycharmProjects/tensorflow/Python/sorted.py
[[100], [17, 240], [180, 18, 3], [58, 103, 48, 340], [22, 24, 25, 33, 44]]