有这个代码:
lista = [3,4,5,2,1,6,8,3]
print lista # [3, 4, 5, 2, 1, 6, 8, 3]
lista.sort(cmp=lambda x,y: cmp(y,x)) # sort descending
print lista # [8, 6, 5, 4, 3, 3, 2, 1] -- it is sorted
lista = [3,4,5,2,1,6,8,3]
print lista # [3, 4, 5, 2, 1, 6, 8, 3]
lista.sort(cmp=lambda x,y: y > x) # sort descending
print lista # [3, 4, 5, 2, 1, 6, 8, 3] -- nothing happens
Run Code Online (Sandbox Code Playgroud)
为什么第二个块中的lambda函数不对数字进行排序?
甲cmp函数需要返回一个负或正数,以指示哪些元件应该首先去(除非它们是相等的,则返回0).你的cmp功能y > x只会返回0或1.尝试将其更改为以下内容:
lista.sort(cmp=lambda x,y: (y > x) - (y < x))
Run Code Online (Sandbox Code Playgroud)
我从Python 3文档中获取了这个:
如果您确实需要该
cmp()功能,可以使用表达式(a > b) - (a < b)作为等效项cmp(a, b).
| 归档时间: |
|
| 查看次数: |
9054 次 |
| 最近记录: |