sorting question

B

belinda thom

Hi,

I've had a look at http://wiki.python.org/moin/HowTo/Sorting, but am
not sure if I can get the operator.itemgetter to do what I want for
my particular need. I'm also not sure why creating my own cmp for
pulling tuple parts out and passing it to a list sort doesn't just work.

I'm sure this stuff is old hat to many on this list. Suggestions
happily accepted.

Suppose I've got a list like:

l = [(-.3,(4,3)),(.2,(5,1)),(.10,(3,2))]

and I want to sort on the 2nd item in the 2nd tuple.

I've tried things like:

cmp = lambda x,y : x[1][1] > y[1][1]
l.sort(cmp=cmp)

but l isn't then changed in place.

Using

sorted(l,operator.itemgetter(1))

behaves as I'd expect, but I really want something like
operator.itemgetter(1).itemgetter(1), which (understandably) causes a
syntax error.

Thx,

--b
 
M

Michael Hoffman

belinda said:
Hi,

I've had a look at http://wiki.python.org/moin/HowTo/Sorting, but am not
sure if I can get the operator.itemgetter to do what I want for my
particular need. I'm also not sure why creating my own cmp for pulling
tuple parts out and passing it to a list sort doesn't just work.

I'm sure this stuff is old hat to many on this list. Suggestions happily
accepted.

Suppose I've got a list like:

l = [(-.3,(4,3)),(.2,(5,1)),(.10,(3,2))]
>
> and I want to sort on the 2nd item in the 2nd tuple.

sorted(l, key=lambda item: item[1][1])
I've tried things like:

cmp = lambda x,y : x[1][1] > y[1][1]
l.sort(cmp=cmp)

Don't call your comparison function cmp. There's already a built-in,
which is what you should be using:

l.sort(cmp=lambda x, y: cmp(x[1][1], y[1][1]))

cmp returns -1, 0, or 1, but your function only returned 0 or 1.

But using key is better, because the key function has to be run only
once per item. The comparison has to be run for every comparison--which
there can be many of if you are sorting a long list.
but l isn't then changed in place.

Using

sorted(l,operator.itemgetter(1))

behaves as I'd expect, but I really want something like
operator.itemgetter(1).itemgetter(1), which (understandably) causes a
syntax error.

Unless you are doing something really weird, it should cause an
AttributeError, not a SyntaxError.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top