How to sort a list of objects based on an attribute of the objects?

前端 未结 8 2412
北海茫月
北海茫月 2020-11-21 23:30

I\'ve got a list of Python objects that I\'d like to sort by an attribute of the objects themselves. The list looks like:

>>> ut
[,         


        
相关标签:
8条回答
  • 2020-11-22 00:33

    A way that can be fastest, especially if your list has a lot of records, is to use operator.attrgetter("count"). However, this might run on an pre-operator version of Python, so it would be nice to have a fallback mechanism. You might want to do the following, then:

    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
    
    0 讨论(0)
  • 2020-11-22 00:37

    Object-oriented approach

    It's good practice to make object sorting logic, if applicable, a property of the class rather than incorporated in each instance the ordering is required.

    This ensures consistency and removes the need for boilerplate code.

    At a minimum, you should specify __eq__ and __lt__ operations for this to work. Then just use sorted(list_of_objects).

    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]
    
    0 讨论(0)
提交回复
热议问题