看板 Python 關於我們 聯絡資訊
python裡面內建的sorted算是方便的方法, 但是小弟沒能試出來sorted能不能使用自己定義的方式作排序。 小弟現在了解的有: 設一個list=[(9,'abc','def'),(1,'eud','abc'),(4,'edu','xxx')] 如果用 sorted(list,key=lambda x:x[0]) 會輸出 [(1, 'eud', 'abc'), (4, 'edu', 'xxx'), (9, 'abc', 'def')] (順序:1>4>9) sorted(list,key=lambda x:x[2],reverse=True) 會輸出 [(4, 'edu', 'xxx'), (9, 'abc', 'def'), (1, 'eud', 'abc')] (x>d>a) sorted(list,key=lambda x:x[1]) 會輸出[(9, 'abc', 'def'), (4, 'edu', 'xxx'), (1, 'eud', 'abc')] (ab>ed>eu) sorted(list,key=lambda x:x[1][1]) 會輸出[(9, 'abc', 'def'), (4, 'edu', 'xxx'), (1, 'eud', 'abc')] (a"b"c > e"d"u > e"u"d) 那麼,如果小弟想讓list用tuple的第二項排, 並以"aeioubcdf....stwxyz"的方式排序, (預期輸出結果是 [(9,'abc','def'),(1,'eud','abc'),(4,'edu','xxx')]) (因為 ab>eu>ed) 要用什麼方式讓python知道我要的排序方法呢? 還是要加入另外的函式? -- 傑米,炸掉它吧。 ⊙─ ─⊙▂⊙ 碰到問題,用C4就對了! █◤ Adam Savage Jamie Hyneman MYTHBUSTERS by dajidali -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.117.194.168
StubbornLin:他不是有個cmp參數可以讓你丟比較用的函數進去嗎? 05/09 22:36
sbrhsieh:相關的 post: #1AAE94ff 05/09 23:52
抱歉忘了先講, 小弟用的是3.1.2版,似乎沒有cmp... ※ 編輯: KagiJhou 來自: 140.117.194.168 (05/10 08:11)
juiz:你沒事用 python3 作什麼 05/10 10:31
呃......這跟我的問題有什麼關係嗎? 還是3以上的版本沒辦法用自己設計的排列順序? ※ 編輯: KagiJhou 來自: 140.117.194.168 (05/10 10:59)
StubbornLin:Use functools.cmp_to_key() to convert an old-style 05/10 11:03
StubbornLin:cmp function to a key function. 05/10 11:03
StubbornLin:http://0rz.tw/HW75n 05/10 11:03
StubbornLin:http://0rz.tw/w5PLH 05/10 11:08
KagiJhou:試了一下,3.1.2版似乎沒有 cmp_to_key。總之感謝各位。 05/10 23:47
KagiJhou:所以有不使用cmp的方法嗎? 05/11 18:32