tags:

views:

98

answers:

1

Hi,

I was wondering how can I make python order my collection of tuples so that first similar items would appear grouped and groups ordered by first item.

order group
3     1
4     2
2     2
1     1

After sort

order group
1     1
3     1
2     2
4     2

Python list

unordered = [(3, 1), (4, 2), (2, 2), (1, 1)]
+4  A: 

I assume you meant unordered = [(3, 1), (4, 2), (2, 2), (1, 1)] because that part of your example as you typed it is incompatible with the other two, right?

If so, then

>>> import operator
>>> sorted(unordered, key=operator.itemgetter(1,0))
[(1, 1), (3, 1), (2, 2), (4, 2)]

or similarly unordered.sort(key=operator.itemgetter(1,0)) if you wanted to sort in place (which given the variable name I'm pretty sure you don't -- it would be seriously weird to name a variable "unordered" if it's meant to be ordered!-).

Alex Martelli
Yes, I meant (1, 1). I fixed the question
Sergej Andrejev
Thanks, this worked like a charm
Sergej Andrejev
You could also, in this particular case, sort with key=lambda (a,b): (b,a). Python's natural sorting of tuples starts with the leftmost term and moves right; you're trying to sort in the opposite direction.
Russell Borogove
@Russell, yes, but the `lambda`'s way slower than the `itemgetter`.
Alex Martelli
@Alex - On a longer list, timeit is showing your way about 12% faster. I tried dis() to see why there was a difference; did it fail to disassemble itemgetter because it's native code?
Russell Borogove
@Russell, yep -- itemgetter (and attrgetter) are native code. To measure the actual speed vs lambda don't do a sort in addition to both of course, just a loop of pure key-extraction;-).
Alex Martelli
Well, that's rather stacking the deck ;) -- good to know though, thanks.
Russell Borogove