update: lambda expression example for python sort (#26044)
Added example that use lambda expression as key during sorting list.
This commit is contained in:
committed by
Christopher McCormack
parent
71b5c71da1
commit
5d5a29649f
@ -71,6 +71,17 @@ b.sort(key = compareByAge)
|
||||
#Output
|
||||
print b # prints [('Adam', 20), ('Rahul', 25), ('Rahman', 30)]
|
||||
```
|
||||
You can also use <b>Lambda expression</b> instead of full function to define key. <br>Here is example of sorting strings based on last two characters:
|
||||
```py
|
||||
# Our strings can contain any characters and we want to sort them based on last two of them
|
||||
strings = ["apple_05", "orange_01", "strawberry_03", "pear_04", "banana_02"]
|
||||
|
||||
# Take just last two characters as key value
|
||||
strings.sort(key = lambda x: x[-2:])
|
||||
|
||||
# Output
|
||||
print strings # Prints ['orange_01', 'banana_02', 'strawberry_03', 'pear_04', 'apple_05']
|
||||
```
|
||||
|
||||
### Sorting Basics
|
||||
|
||||
|
Reference in New Issue
Block a user