Difficulty Sorting Tuples with itemgetter
I'm new to Python as the screen name attests. I was attempting to sort a
list of tuples, think (x,y) pairs in a list and ran into a problem. My
goal is to sort the list of tuples by the x variables in ascending order
primarily but then sort
I investigated the wiki on HowToSort at
http://wiki.python.org/moin/HowTo/Sorting/ and thought I would try the
operator module and the itemgetter function as a key.
The simple sorted() function can sort the tuple fine, but when you want
one index ascending and one ascending, I'm lost. Here is the code:
from operator import itemgetter, attrgetter
ItemList = [(1,7),(2,1),(1,5),(1,1)]
# Want list sorted with X values descending, then y values ascending
# expected [(2, 1), (1, 1), (2, 1), (1, 7)]
print
print ' Input:', ItemList
print 'Output1:',sorted(ItemList, reverse = True)
print
print ' Input:', ItemList
print 'Output2:', sorted(ItemList, key = itemgetter(-0,1))
print
print ' WANTED:', '[(2, 1), (1, 1), (2, 1), (1, 7)]'
with the following output:
Input: [(1, 7), (2, 1), (1, 5), (1, 1)]
Output1: [(2, 1), (1, 7), (1, 5), (1, 1)]
Input: [(1, 7), (2, 1), (1, 5), (1, 1)]
Output2: [(1, 1), (1, 5), (1, 7), (2, 1)]
WANTED: [(2, 1), (1, 1), (2, 1), (1, 7)]
I obviously, do not understand the itemgetter function, so any help would
be appreciated on that.
Also, any ideas on how to do the two sort on (x,y) pairs? I am hoping to
avoid a lambda solution but I'm sure that's where this is going. Thanks.
No comments:
Post a Comment