Is there any other argument than key
, for example: value
?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to toggle on Order in ReactJS
- How to get the background from multiple images by
- PHP Recursively File Folder Scan Sorted by Modific
Arguments of
sort
andsorted
Both
sort
andsorted
have three keyword arguments:cmp
,key
andreverse
.Using
key
andreverse
is preferred, because they work much faster than an equivalentcmp
.key
should be a function which takes an item and returns a value to compare and sort by.reverse
allows to reverse sort order.Using
key
argumentYou can use
operator.itemgetter
as 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
key
argument tosort
orsorted
.itemgetter
, in particular, creates such a function that fetches the given item from its operand. An example from its documentation:Mini-benchmark,
key
vscmp
Just out of curiosity,
key
andcmp
performance compared, smaller is better:So, sorting with
key
seems to be at least twice as fast as sorting withcmp
. Usingitemgetter
instead oflambda x: x[1]
makes sort even faster.Yes, it takes other arguments, but no
value
.What would a
value
argument even mean?Besides
key=
, thesort
method of lists in Python 2.x could alternatively take acmp=
argument (not a good idea, it's been removed in Python 3); with either or none of these two, you can always passreverse=True
to have the sort go downwards (instead of upwards as is the default, and which you can also request explicitly withreverse=False
if you're really keen to do that for some reason). I have no idea what thatvalue
argument you're mentioning is supposed to do.