views:

141

answers:

4
[(u'we', 'PRP'), (u'saw', 'VBD'), (u'you', 'PRP'), (u'bruh', 'VBP'), (u'.', '.')]

I want to order this alphabetically, by "PRP, VBD, PRP, and VBP" It's not the traditional sort, right?

+15  A: 

Use itemgetter:

>>> a = [(u'we', 'PRP'), (u'saw', 'VBD'), (u'you', 'PRP'), (u'bruh', 'VBP'), (u'.', '.')]
>>> import operator
>>> a.sort(key = operator.itemgetter(1))
>>> a
[(u'.', '.'), (u'we', 'PRP'), (u'you', 'PRP'), (u'saw', 'VBD'), (u'bruh', 'VBP')]
slurdge
+1 for the use of `itemgetter`, didn't know it existed :)
abyx
+1 for using key instead of cmp.
SpoonMeiser
Acceptable solution ... but I don't think it's worth an import. :) I prefer Dave Webb's way.
jellybean
+1  A: 

You can pass a comparison function in the sort method.

Example:

l = [(u'we', 'PRP'), (u'saw', 'VBD'), (u'you', 'PRP'), (u'bruh', 'VBP'), (u'.', '.')]
l.sort(lambda x, y: cmp(x[1], y[1])) # compare tuple's 2nd elements

Output:

>>> l
[(u'.', '.'),
 (u'we', 'PRP'),
 (u'you', 'PRP'),
 (u'saw', 'VBD'),
 (u'bruh', 'VBP')]
>>>
Nick D
Using a key with sort is preferable to using cmp, as the key only gets called N times where cmp will be called NlogN times. You have no choice in python3, support for cmp has been removed
gnibbler
@gnibbler, thanks for the tip. Why the key will be called only N times? I didn't know that.
Nick D
@Nick, because with `key` Python will go through the list once to calculate the keys, then sort using those keys. With `cmp`, on the other hand, it will call the function every time it needs to compare two values.
Daniel Roseman
hmm, so it collects the keys prior sorting. Thanks. But won't this step use extra memory? Is it really faster than using the `cmp`, for large lists? I have to test the 2 approaches ;-)
Nick D
+7  A: 

The sort method takes a key argument to extract a comparison key from each argument, i.e. key is a function which transforms the list item into the value you wish to sort on.

In this case it's very easy to use a lambda to extract the second item from each tuple:

>>> mylist = [(u'we', 'PRP'), (u'saw', 'VBD'), (u'you', 'PRP'), (u'bruh', 'VBP')
, (u'.', '.')]
>>> mylist.sort(key = lambda x: x[1])
>>> mylist
[(u'.', '.'), (u'we', 'PRP'), (u'you', 'PRP'), (u'saw', 'VBD'), (u'bruh', 'VBP')]
Dave Webb
Actualy, it is the same as itemgetter but at least you see what's it is doing.
Natim
A: 

Or use the Built-in Function sorted (similar to Nick_D's answer):

ls = [(u'we', 'PRP'), (u'saw', 'VBD'), (u'you', 'PRP'), (u'bruh', 'VBP'), (u'.', '.')]


sorted(ls, cmp=lambda t1, t2: cmp(t1[1], t2[1]))
Jogusa