自定义Python列表排序 [英] Custom Python list sorting

查看:82
本文介绍了自定义Python列表排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在重构我的一些旧代码,并且发现了这一点:

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

该代码有效(并且我是3年前写的!),但是我找不到在Python文档中任何地方记录的东西,并且每个人都使用sorted()来实现自定义排序.有人可以解释为什么这样做吗?

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?

推荐答案

此处一个>.

sort()方法采用可选参数来控制 比较.

The sort() method takes optional arguments for controlling the comparisons.

cmp指定两个参数的自定义比较功能(列表 项),其应返回负数,零或正数 取决于第一个参数是否小于 等于或大于第二个参数:cmp = lambda x,y: cmp(x.lower(),y.lower()).默认值为无.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆