Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- >>> ut
- [<Tag: 128>, <Tag: 2008>, <Tag: <>, <Tag: actionscript>, <Tag: addresses>,
- <Tag: aes>, <Tag: ajax> ...]
- >>> ut[1].count
- 1L
- # To sort the list in place...
- ut.sort(key=lambda x: x.count, reverse=True)
- # To return a new list, use the sorted() built-in function...
- newlist = sorted(ut, key=lambda x: x.count, reverse=True)
- try: import operator
- except ImportError: keyfun= lambda x: x.count # use a lambda if no operator module
- else: keyfun= operator.attrgetter("count") # use operator since it's faster than lambda
- ut.sort(key=keyfun, reverse=True) # sort in-place
- ut.sort(key=lambda x: x.count, reverse=True)
- #!/usr/bin/env python
- import random
- class C:
- def __init__(self,count):
- self.count = count
- def __cmp__(self,other):
- return cmp(self.count,other.count)
- longList = [C(random.random()) for i in xrange(1000000)] #about 6.1 secs
- longList2 = longList[:]
- longList.sort() #about 52 - 6.1 = 46 secs
- longList2.sort(key = lambda c: c.count) #about 9 - 6.1 = 3 secs
- from operator import attrgetter
- ut.sort(key = attrgetter('count'), reverse = True)
- ut = Tag.objects.order_by('-count')
- class Card(object):
- def __init__(self, rank, suit):
- self.rank = rank
- self.suit = suit
- def __eq__(self, other):
- return self.rank == other.rank and self.suit == other.suit
- def __lt__(self, other):
- return self.rank < other.rank
- hand = [Card(10, 'H'), Card(2, 'h'), Card(12, 'h'), Card(13, 'h'), Card(14, 'h')]
- hand_order = [c.rank for c in hand] # [10, 2, 12, 13, 14]
- hand_sorted = sorted(hand)
- hand_sorted_order = [c.rank for c in hand_sorted] # [2, 10, 12, 13, 14]
Add Comment
Please, Sign In to add comment