Hacker News new | ask | show | jobs
by rmc 4567 days ago
Python has this with the "key" argument to "sort".

    list.sort(key=lambda x: x.lower())
2 comments

You can also pass in the method from the str type:

    key=str.lower
It will be faster, but it will break on elements that aren't strings (which could be good or bad).
Then you can use

  key=operator.methodcaller("lower")
and handle any type.
witch is a little different thing.

python can sort according to a function (using the "key" parameter) or using a custom comparator function (using the "cmp" parameter)

as a side note, Python offers also a sorted[0] function, applyable to any sequence

[0] http://docs.python.org/2/library/functions.html#sorted

I don't get the difference.
They resolve differenti problems: say you have a list of complex object, and you wanna sort by an attribute, you can use

    mylist.sort(key=lambda element: element.attribute)
Elsewere, say you want to sort a non-omogeneous list, or according to a custom order (attribute1 descending, attribute2 ascending) cmp make this easy
I think ve was saying, ve doesn't see the difference between python's `sort(key=...)` and perl6's `sort { one-arg block }`. (At any rate, I don't see that difference.)
Elsewere, say you want to sort a non-omogeneous list, or according to a custom order (attribute1 descending, attribute2 ascending) cmp make this easy

You can do this in python with the key function returning a list/tuple:

    mylist.sort(key=lambda element: (element.attribute1, -element.attribute2))
I'm not sure you can do -"string" :)
The Python .sort() method sorts in-place. The sorted() function returns a sorted copy, leaving the original untouched.
I realize this is drifting off topic, and I could well believe the current Rakudo implementation doesn't actually save the memory (I could believe it does, I just don't know) but P6, for any method, including sort:

    my $a = [2,1]; say $a.sort;  say $a # 1 2 2 1
    my $a = [2,1]; say $a.=sort; say $a # 1 2 1 2
This riffs off the general op= syntax:

    my $a = 1; say $a +  1; say $a # 2 1
    my $a = 1; say $a += 1; say $a # 2 2
I meant I didn't understand the difference between Python's sort(key=..) and what's described here for Perl.
what is described for perl is python's sort(cmp=...)
Hmm? I thought the whole point of the article was "Most people know about sort(cmp=), which takes two parameters. But check out sort(key=), it only takes one parameter, which means the key function only has to run once per item", but for Perl.
And incomprehensibly, Python 3 removed the cmp argument, leaving only unwary sort.