sort 與 sorted 區別:
sort 只是應用在 list 上的方法,(就地排序無返回值)。
sorted 是內建函數,可對所有可迭代的對象進行排序操作,(返回新的list)。
語法
sorted 語法:
sorted(iterable, key=None, reverse=False)
參數說明:
- iterable -- 可迭代對象。
- key -- 主要是用來進行比較的元素,只有一個參數,具體的函數的參數就是取自於可迭代對象中,指定可迭代對象中的一個元素來進行排序。
- reverse -- 排序規則,reverse = True 降序 , reverse = False 升序(默認)。
實例
>>>a = [5,7,6,3,4,1,2] >>> b = sorted(a) >>> a [5, 7, 6, 3, 4, 1, 2] >>> b [1, 2, 3, 4, 5, 6, 7]
>>> L=[('b',2),('a',1),('c',3),('d',4)]
>>> sorted(L, key=lambda x:x[1]) [('a', 1), ('b', 2), ('c', 3), ('d', 4)] >>> students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)] >>> sorted(students, key=lambda s: s[2]) [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
>>> sorted(students, key=lambda s: s[2], reverse=True) [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)] >>>
練習
假設我們用一組tuple表示學生名字和成績: L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
用sorted()對上述列表: (1)按名字排序: (2)按成績從高到低排序:
答案:
>>> print('sorted_by_name:', sorted(L, key=lambda x: x[0]))
sorted_by_name: [('Adam', 92), ('Bart', 66), ('Bob', 75), ('Lisa', 88)] >>>print('sorted_by_score:', sorted(L, key=lambda x: x[1], reverse=True)) sorted_by_score: [('Adam', 92), ('Lisa', 88), ('Bob', 75), ('Bart', 66)]