Python排列函數:sort、sorted

排序函數介紹:sort()和sorted()都屬於Python list的排序方法python

區別:sort()屬於永久性排列,直接改變該list; sorted屬於暫時性排列,會產生一個新的序列。函數

#sorted()
>>> sorted([5, 2, 3, 1, 4])
[1, 2, 3, 4, 5]

#sort()
>>> L = [5, 2, 3, 1, 4]
>>> L.sort()
>>> print L
[1, 2, 3, 4, 5]

 

#sort後會返回None
def paixu(list):
    return list.sort()

paixu(['a','f','g','b','a'])

#並沒輸出結果,返回None

#sorted後會返回列表
def paixu(list):
    return sorted(list)

paixu(['a','f','g','b','a'])

#輸出結果
['a', 'a', 'b', 'f', 'g']

 

如下對經常使用的sorted進行介紹:this

python 內置的sorted()函數能夠對一個list進行排序:spa

>>> sorted([8,3,8,11,-2])
[-2, 3, 8, 8, 11]

既然說是高階函數,那麼它還能夠接受一個key函數來實現自定義的排序,好比按照絕對值大小進行排序:code

>>> sorted([8,3,8,11,-9],key=abs)
[3, 8, 8, -9, 11]

key指定的函數將做用於list中的每個元素上,根據key函數返回的結果進行排序。blog

來看看字符串排序的問題排序

>>> sorted(['abc','Abc','Cba','bAc'])
['Abc', 'Cba', 'abc', 'bAc']

默認的,對於字符串,sorted函數按照ASCII的大小進行排序,由於C<a,大寫的C會排在小寫的a前面。字符串

若是咱們想要達到忽略大小寫的排序,只須要更改一下key函數:string

>>> sorted(['abc','Abc','Cba','bAc'],key=str.lower)
['abc', 'Abc', 'bAc', 'Cba']

結合lambda關鍵字按年齡排序:it

 

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)]

 

進一步,要進行反向排序,能夠傳入第三個參數reverse=True:

>>> sorted(['abc','Abc','Cba','bAc'],key=str.lower,reverse=True)
['Cba', 'bAc', 'abc', 'Abc']

sorted()排序的關鍵在於實現一個映射函數!

練習:

把一句話的每一個單詞按照開頭的字母排序

思路:根據空格用split()把字符串變成list,而後用sort或者sorted排序

 

# change this value for a different result

my_str = "Hello this Is an Example With cased letters"

#第一種方法:這段長代碼很難受
'''
a = my_str.upper()
print(a)
b = a.split(' ')
print(b)
b.sort()
print(b)
#your solution here
'''

#第二種方法:結合key關鍵字一條就出來了
sorted(my_str.split(),key=str.lower)

#輸出結果
['an', 'cased', 'Example', 'Hello', 'Is', 'letters', 'this', 'With']

#第三種,無視大小寫排序
# breakdown the string into a list of words
words = my_str.split()

# sort the list
words.sort()

# display the sorted words

print("The sorted words are:")
for word in words:
    print(word, end=' ')

#輸出結果
The sorted words are:
Example Hello Is With an cased letters this 

 

 

 

 

用一組tuple表示學生名字和成績:L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)],而後分別按名字和成績排序

思路:定義兩個函數用用t[0]和t[1]分別表示名字和成績,而後用sort或sorted排序

#按名字字母排序
>>> L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
>>> def by_name(t):
    return t[0]     #t[0]表示名字 >>> L2 = sorted(L,key = by_name)
>>> print(L2)
[('Adam', 92), ('Bart', 66), ('Bob', 75), ('Lisa', 88)]

#按成績低到高排序 >>> def by_score(t):
    return t[1]     #t[1]表示成績 >>> L2 = sorted(L,key = by_score)
>>> print(L2)
[('Bart', 66), ('Bob', 75), ('Lisa', 88), ('Adam', 92)]
相關文章
相關標籤/搜索