开发者

How do I order this list in Python?

[(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 开发者_如何学Ctraditional sort, right?


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')]


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')]


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')]
>>> 


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]))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜