自定义 Python 列表排序 [英] Custom Python list sorting
问题描述
我在重构我的一些旧代码时遇到了这个:
alist.sort(cmp_items)def cmp_items(a, b):如果 a.foo >b.foo:返回 1elif a.foo == b.foo:返回 0别的:返回-1
代码有效(我是在大约 3 年前写的!)但是我在 Python 文档的任何地方都找不到这个东西,每个人都使用 sorted()
来实现自定义排序.有人能解释一下为什么会这样吗?
一>.
<块引用>sort() 方法采用可选参数来控制比较.
cmp 指定两个参数的自定义比较函数(列表items) 应该返回一个负数、零或正数取决于第一个参数是否被认为小于,等于或大于第二个参数:cmp=lambda x,y:cmp(x.lower(), y.lower()).默认值为无.
I was refactoring some old code of mine and came across of this:
alist.sort(cmp_items)
def cmp_items(a, b):
if a.foo > b.foo:
return 1
elif a.foo == b.foo:
return 0
else:
return -1
The code works (and I wrote it some 3 years ago!) but I cannot find this thing documented anywhere in the Python docs and everybody uses sorted()
to implement custom sorting. Can someone explain why this works?
It's documented here.
The sort() method takes optional arguments for controlling the comparisons.
cmp specifies a custom comparison function of two arguments (list items) which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument: cmp=lambda x,y: cmp(x.lower(), y.lower()). The default value is None.
这篇关于自定义 Python 列表排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!