سؤال

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

Felt sorry for my ignorance, I don't understand how this lambda function is working, all I know about cmp is to give +1/1/0 to show the result of comparison,len gives the length of the string How did the lambda function take the arguments? in pairs? taking in 1st,2nd then 3rd,4th ? and what is the sort doing here? Thank you so much for any help!

هل كانت مفيدة؟

المحلول 2

Perhaps it's easier to understand using a regular function

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

The lambda function really isn't better that the regular function here. It's harder to document and test.

Aside: cmp is deprecated in Python2, so you should use a key function instead.

def key_function(x):
    return len(x)

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

As in @Roman's answer, this key_function is just a wrapper around len, so you may write

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

As an exercise, you could add a print statement to cmp_function and key_function - see how many times each is called. Compare this with the number of items in a

نصائح أخرى

why not use key?

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

If you want to use old-style sorting with cmp, you have do define function cmp like 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

so in your case it could be something like:

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

This function used to compare two elements in comparison-based sort (Timsort, if I'm not mistaken)

Roman Pekar explains how you should do this.

But why does your version work?


There are two different things named cmp here:

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

First, that cmp= means you're passing a function as a keyword argument named cmp. As the docs explain (in note 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.

Second, what you're passing to that is a wrapper around the builtin cmp function, which does this:

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.

So, you're saying that to compare two list items x and y, it should call cmp(len(x), len(y)). In other words, sort them by length.


If you don't understand how lambda x, y: cmp(len(x), len(y)) means that…

A lambda expression is just a way of defining simple functions in the middle of an expression. This:

lamdba a, b, c: <some expression>

… defines the exact same function as:

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

… except that it doesn't have a name, and can be used in the middle of an expression. So, your lambda is the same as:

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

The Lambda forms section of the tutorial explains this… although not in any more depth, and the Lambdas section of the reference docs is only slightly more detailed.


As gnibbler and Roman both point out, using cmp instead of key is deprecated (and illegal, in Python 3), and shouldn't be done unless you really need to work with Python 2.3 or earlier.

As gnibbler also points out, using lambda when you don't need to is a recipe for confusion.

So, Roman's answer is exactly what you should do instead of this.

The Sorting HowTo in the docs has a nice explanation of all of this.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top