A small question about lambda

persons= [{"name":" Jon"," age": 32}, {"name":" Alan"," age": 50}, {"name":"Bob"," age":23}]

sorted (persons, key = lambda x: (x ["name"],-x [" age"])

persons

[{"age": 32," name": "Jon"},
{" age": 50, "name":" Alan"},
{"age": 23," name": "Bob"}]

output result:

[{"age": 50," name": "Alan"},
{" age": 23, "name":" Bob"},
{"age": 32," name": "Jon"}]

this is an explanation of the sorted function. I know that key receives a function here, but I can"t understand how to sort the x and-x in it. I hope the seniors can give me some advice and thank you in advance.

Mar.03,2021

sorting is based on comparison. So the comparison of name is a positive comparison, that is, smaller names = smaller objects = higher, larger names = larger objects = later , which can be sorted by name.

the second -age means that between objects with the same name (for example, several people whose names are called John), a negative comparison of age is used, that is, those who are older are considered younger (at the top of the list), and those who are younger are considered older (at the bottom of the list).


the function of lambda has been clearly explained by @ code poet Taro

.

what I want to add is about how this sorted is sorted

if the sort keyword is a tuple, such as ('axiom, 1) and (' bounded, 0) sort, the collation starts with the first element of the tuple and then compares until it encounters an unequal one. At this time, the corresponding element of the tuple is larger. Similar to dictionary order

so this sorted means to sort by name first, and by age if the name is the same

.
(x ['name'],-x [' age'])
The default comparison order for

tuples and other iterable objects (such as the first item string of tuples) is in the order of elements, and the order type is positive order.
numbers are compared by size. The positive order is from small to large, and the "-" sign is the opposite number, according to the positive order of the opposite number, that is, the reverse order from large to small.
so the overall meaning is to go first by name (character set order), and again by age.

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b35794-40fd9.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b35794-40fd9.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?