使用Python的lambda函数排列字符串数

2024-05-13 20:19:02 发布

您现在位置:Python中文网/ 问答频道 /正文

a=['green egg','snail and lettuce','bacon','dorse naga','rutabaga ripple','cheese']
a.sort(cmp=lambda x,y:cmp(len(x),len(y)))
print a

很抱歉我的无知,我不明白这个lambda函数是怎么工作的,我只知道cmp给+1/1/0来显示比较的结果,len给出了字符串的长度 lambda函数是如何接受参数的?两人一组?第一,第二然后第三,第四? 这类人在这里干什么? 非常感谢你的帮助!在


Tags: andlambda函数lenegggreenbaconcmp
3条回答

也许使用常规函数更容易理解

def cmp_function(x, y):
    return cmp(len(x), len(y))

a = ['green egg','snail and lettuce','bacon','dorse naga','rutabaga ripple','cheese']
a.sort(cmp=cmp_function)
print a

lambda函数并没有这里的正则函数好。更难记录和测试。在

Aside:cmp在Python2中不推荐使用,因此您应该改用key函数。在

^{pr2}$

正如@Roman的回答一样,这个key_function只是len的包装,所以您可以写

a = ['green egg','snail and lettuce','bacon','dorse naga','rutabaga ripple','cheese']
a.sort(key=len)
print a

作为练习,您可以向cmp_functionkey_function添加一个print语句,看看每个语句被调用了多少次。将其与a中的项数进行比较

为什么不使用key?在

a = ['green egg','snail and lettuce','bacon','dorse naga','rutabaga ripple','cheese']
a.sort(key=len)

如果要对cmp使用旧式排序,则必须定义函数cmplike this

That function should take two arguments to be compared and then return a negative value for less-than, return zero if they are equal, or return a positive value for greater-than

所以在你的情况下可能是这样的:

^{pr2}$

此函数用于比较基于比较的排序中的两个元素(Timsort,如果我没弄错的话)

罗曼·佩卡尔解释了你应该怎样做。在

但为什么你的版本有效呢?在


这里有两个不同的名称为cmp

a.sort(cmp=lambda x,y:cmp(len(x),len(y)))

首先,cmp=意味着您将传递一个名为cmp的关键字参数。正如the docs解释的那样(在注释8中):

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.

其次,传递给它的是一个关于内置^{}函数的包装器,它执行以下操作:

Compare the two objects x and y and return an integer according to the outcome. The return value is negative if x < y, zero if x == y and strictly positive if x > y.

所以,您的意思是要比较两个列表项x和{},它应该调用cmp(len(x), len(y))。换句话说,按长度排序。在


如果你不明白lambda x, y: cmp(len(x), len(y))是什么意思

lambda表达式只是在表达式中间定义简单函数的一种方法。这个:

^{pr2}$

…定义的函数与:

def f(a, b, c): return <expression>

…只是它没有名称,可以在表达式的中间使用。因此,您的lambda与:

def f(x, y): return cmp(len(x), len(y))

本教程的Lambda forms部分解释了这一点……尽管没有更深入地解释,参考文档的Lambdas部分只是稍微更详细一些。在


{12{3}在Python和cdgni3}中都是非法的,除非你使用的是Python和cdgni3}都是非法的。在

正如gnibbler也指出的那样,在不需要的时候使用lambda是造成混淆的一个方法。在

所以,罗曼的答案正是你应该做什么来代替这个。在

文档中的Sorting HowTo对所有这些都有很好的解释。在

相关问题 更多 >