Note that you may forget how to sort when you are competing in Python3
Below, since we are running in interpreted mode, think of what has a >>>>
at the beginning of the line as input.
list.sort ()
sorts the original list. The return value is None
>>>> list = [2, 3, 5, 1, 4]
>>>> list.sort()
>>>> list
[1, 2, 3, 4, 5]
sorted (list)
returns the result of sorting without changing the original list
>>>> list = [2, 3, 5, 1, 4]
>>>> sorted(list)
[1, 2, 3, 4, 5]
>>>> list
[2, 3, 5, 1, 4]
Below, both list.sort ()
and sorted (list)
use the same options, so only sorted (list)
is handled.
Optionally specify reverse = True
>>>> list = [2, 3, 5, 1, 4]
>>>> sorted(list)
[1, 2, 3, 4, 5]
>>>> sorted(list, reverse=True)
[5, 4, 3, 2, 1]
When sorting normally, it sorts in order from the left column. Image like dictionary order
>>>> people = [('Bob', 12), ('Alice', 10), ('Chris', 8), ('Chris', 7)]
>>>> sorted(people)
[('Alice', 10), ('Bob', 12), ('Chris', 7), ('Chris', 8)]
When you want to use only the second column for sorting
>>>> sorted(people, key=lambda x:x[1])
[('Chris', 7), ('Chris', 8), ('Alice', 10), ('Bob', 12)]
When you want to use the 1st and 2nd columns for sorting
>>>> sorted(people, key=lambda x:(x[0], x[1]))
[('Alice', 10), ('Bob', 12), ('Chris', 7), ('Chris', 8)]
If you use ʻitemgetter, ʻattrgetter
, you don't have to write a lambda expression, but I decided not to use it because I will learn more.
If you want to use it, please check it from the reference link.
https://docs.python.org/3/howto/sorting.html
Recommended Posts