新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:python怎么從小到大排列
python提供了對list排序兩種方法

1、使用list內(nèi)置函數(shù)sort排序
list.sort(key=None,reverse=False)
eg:
In [57]: l=[27,47,3,42,19,9] In [58]: l.sort() In [59]: l Out[59]: [3, 9, 19, 27, 42, 47]
上面這種是直接對l列表里面的元素排序,sort()函數(shù)還提供了一個key參數(shù),這個參數(shù)的值是一個函數(shù),這個函數(shù)只能有一個返回值,且返回值用來進行比較。 這個技術是快速的因為key指定的函數(shù)將準確地對每個元素調(diào)用。
In [53]: L = [('b',6),('a',1),('c',3),('d',4)]
In [54]: L.sort(key=lambda x:x[1])
In [56]: L
Out[56]: [('a', 1), ('c', 3), ('d', 4), ('b', 6)]上面那段話,再結(jié)合這個例子,我是這樣理解的:匿名函數(shù)lambda x:x[1]相當于:
def f(x): return x[1]
key參數(shù)接受列表L里的每個元素的第二個參數(shù),根據(jù)第二個參數(shù)的排序,確定整體的排序。也就是說,設置了key參數(shù)后,key接收的值代表了整體,排序的標準就變成了對key所接收的值進行排序。
2、使用python內(nèi)置函數(shù)sorted排序
sorted方法和sort方法很相似,不同的是,sorted不改變原來的列表,并返回一個排好序的列表。而list.sort()是改變了原有的列表。還有就是,list.sort()只能對列表排序,而sorted()可以對其他數(shù)據(jù)結(jié)構(gòu)排序。
In [62]: l=[27,47,3,42,19,9] In [63]: sorted(l) Out[63]: [3, 9, 19, 27, 42, 47]
sorted方法同樣可以用key參數(shù),用法也是一樣的。
In [68]: data=[{'name':'Abbie','score':99},{'name':'Ivy','score':80}]
In [69]: sorted(data,key=lambda x:x['score'])
Out[69]: [{'name': 'Ivy', 'score': 80}, {'name': 'Abbie', 'score': 99}]python學習網(wǎng),免費的在線學習python平臺,歡迎關注!
文章標題:創(chuàng)新互聯(lián)Python教程:python怎么從小到大排列
網(wǎng)站網(wǎng)址:http://fisionsoft.com.cn/article/dpjshgd.html


咨詢
建站咨詢
