RexMan85
RexMan85

Reputation: 59

Sort with two key value

I'm trying to convert a code, and I ran into this line, and I'm not sure what it does. I know I can sort using a key like a:a*a, but how does it handle two keys?

this is the line I am trying to convert (to C#, if it matters):

 arr.sort(lambda a,b:a-b)

Upvotes: 1

Views: 79

Answers (2)

Tobia Tesan
Tobia Tesan

Reputation: 1936

https://docs.python.org/2/tutorial/datastructures.html

list.sort(cmp=None, key=None, reverse=False)

Sort the items of the list in place (the arguments can be used for sort customization, see sorted() for their explanation).

https://docs.python.org/2/library/functions.html#sorted

cmp specifies a custom comparison function of two arguments (iterable elements) 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.

lambda a,b is for defining an anonymous function in Python.

So this is the same as

def f(a,b):
    return a-b

arr.sort(f)

Which naturally returns > 0 if a > b and 0 if a==b.

As @MartijnPieters points out, this should be plain "natural" sorting and, were we in the absence of operator overloading (e.g. plain integers), it would be the same as sort() with no arguments.

Upvotes: 1

Pedro Witzel
Pedro Witzel

Reputation: 368

You are sorting the array arr by passing the sorting comparison function as a lambda.

Lambdas are small locally defined functions, witch are also available in C#.

Finally, the call sorts the array based on the difference of variable.

Upvotes: 0

Related Questions