作者KagiJhou (Kagi)
看板Python
标题[问题] 如何自行定义排序方法
时间Sun May 9 22:13:42 2010
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
1F:推 StubbornLin:他不是有个cmp参数可以让你丢比较用的函数进去吗? 05/09 22:36
2F:→ sbrhsieh:相关的 post: #1AAE94ff 05/09 23:52
抱歉忘了先讲,
小弟用的是3.1.2版,似乎没有cmp...
※ 编辑: KagiJhou 来自: 140.117.194.168 (05/10 08:11)
3F:→ juiz:你没事用 python3 作什麽 05/10 10:31
呃......这跟我的问题有什麽关系吗?
还是3以上的版本没办法用自己设计的排列顺序?
※ 编辑: KagiJhou 来自: 140.117.194.168 (05/10 10:59)
4F:推 StubbornLin:Use functools.cmp_to_key() to convert an old-style 05/10 11:03
5F:→ StubbornLin:cmp function to a key function. 05/10 11:03
8F:→ KagiJhou:试了一下,3.1.2版似乎没有 cmp_to_key。总之感谢各位。 05/10 23:47
9F:→ KagiJhou:所以有不使用cmp的方法吗? 05/11 18:32