sorted排序的兩個方法 Python

2022-05-23 06:15:15 字數 730 閱讀 8154

在給列表排序時,sorted非常好用,語法如下:

sorted(iterable[, cmp[,key[,reverse]]])

簡單列表排序,很容易完成,sorted(list)返回的物件就是列表結果,但是遇到列表中巢狀元組時,需要使用特殊的方法解決。

問題描述:

給定列表如下:

list_example = [('john', 35), ('jack', 32), ('michael', 28), ('sean', 20)]

輸出要求:

[('sean', 20), ('michael', 28), ('jack', 32), ('john', 35)]

解決方法:

1. 傳入函式給key,完成操作;

2. 直接使用lambda函式;

方法1的**如下:

def revsort(oldlist):

return oldlist[::-1]

def by_age(li):

return sorted(li, key = revsort)

方法2的**如下:

def by_age(li):

return sorted(li, key = lambda x: x[1])

直接print可以得到結果:

print(by_age(list_example))

py程式 兩個判斷回文的程式

a input 輸入一段話 b int len a 算出這段話的字數 c int len a 2 print b if b 2 and a 0 a 1 print 是回文 quit elif b 3 and a 0 a 1 print 是回文 quit elif b c 2 and a c a c ...

python兩個佇列實現乙個棧 py兩個棧實現佇列

純粹是為了提高專注度,逼迫自己放下手機,就來寫一寫這個東西。用兩個棧來實現乙個佇列,leetcode劍指offer第9題,鏈結如下 寫在前面 棧 先進後出 佇列 先進先出 兩者都是限制訪問點的線性結構。解決問題 出棧 list.pop 彈出列表最後乙個元素 list 的 pop 功能實現棧的 pop...

兩個排序演算法

然後貼 1 int num 10 2 time t tms 3 srand unsigned int time tms 生成種子 4for int i 0 i 10 i 生成陣列元素為10 的陣列59 1011 氣泡排序 12for int i 0 i 10 1 i 1324 25 1 int nu...