Home > Net >  How to use the lambda in sorted?
How to use the lambda in sorted?

Time:09-27

sorted(arr, key=lambda x:(self.function(x), x))

What's the meaning of (self.function(x), x)?

CodePudding user response:

This allows sorting by two criteria. If two values are equal for self.function(x), they will be sorted by x.

CodePudding user response:

The key parameter of the sorted method takes in a function reference that returns a key to be used for sorting purposes.

as an example

arr = ["apple", "Andrew", "Cat", "cool"]
print(sorted(arr, key=lambda item: item.lower()))

would sort the items in the arr based on their str.lower representation.

the following snippet

sorted(arr, key=lambda x:(self.function(x), x))

sorts the items in arr based on the tuple (self.function(x), x), see this post to see how python sorts an array of tuples.

  • Related