There is this code:
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
Why does the lambda function in the second block not sort the numbers?
Simply put, a lambda function is just like any normal python function, except that it has no name when defining it, and it is contained in one line of code. A lambda function evaluates an expression for a given argument. You give the function a value (argument) and then provide the operation (expression).
The syntax of the sort() method is: list. sort(key=..., reverse=...) Alternatively, you can also use Python's built-in sorted() function for the same purpose.
Lambda is well-suited for Task states, because Lambda functions are serverless and easy to write. You can write code in the AWS Management Console or your favorite editor. AWS handles the details of providing a computing environment for your function and running it.
In Python, lambda is a keyword used to define anonymous functions(functions with no name) and that's why they are known as lambda functions. Basically it is used for defining anonymous functions that can/can't take argument(s) and returns value of data/expression.
The second example doesn't work because the function you're giving it isn't a valid comparator.
A valid comparator is supposed to
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.
The function lambda x,y: y > x
doesn't fulfil this contract.
A cmp
function needs to return a negative or positive number to indicate which element should go first (unless they are equal, then return 0). Your cmp
function of y > x
will only return 0
or 1
. Try changing it to the following:
lista.sort(cmp=lambda x,y: (y > x) - (y < x))
I took this from the Python 3 docs:
If you really need the
cmp()
functionality, you could use the expression(a > b) - (a < b)
as the equivalent forcmp(a, b)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With