Is there any other argument than key, for example: value?
Is there any other argument than key , for example: value ?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Arguments of
sortandsortedBoth
sortandsortedhave three keyword arguments:cmp,keyandreverse.Using
keyandreverseis preferred, because they work much faster than an equivalentcmp.keyshould be a function which takes an item and returns a value to compare and sort by.reverseallows to reverse sort order.Using
keyargumentYou can use
operator.itemgetteras a key argument to sort by second, third etc. item in a tuple.Example
Explanation
Sequences can contain any objects, not even comparable, but if we can define a function which produces something we can compare for each of the items, we can pass this function in
keyargument tosortorsorted.itemgetter, in particular, creates such a function that fetches the given item from its operand. An example from its documentation:Mini-benchmark,
keyvscmpJust out of curiosity,
keyandcmpperformance compared, smaller is better:So, sorting with
keyseems to be at least twice as fast as sorting withcmp. Usingitemgetterinstead oflambda x: x[1]makes sort even faster.