Sort a list by multiple attributes?

前端 未结 6 1983
后悔当初
后悔当初 2020-11-22 02:48

I have a list of lists:

[[12, \'tall\', \'blue\', 1],
[2, \'short\', \'red\', 9],
[4, \'tall\', \'blue\', 13]]

If I wanted to sort by one e

6条回答
  •  别跟我提以往
    2020-11-22 03:18

    It appears you could use a list instead of a tuple. This becomes more important I think when you are grabbing attributes instead of 'magic indexes' of a list/tuple.

    In my case I wanted to sort by multiple attributes of a class, where the incoming keys were strings. I needed different sorting in different places, and I wanted a common default sort for the parent class that clients were interacting with; only having to override the 'sorting keys' when I really 'needed to', but also in a way that I could store them as lists that the class could share

    So first I defined a helper method

    def attr_sort(self, attrs=['someAttributeString']:
      '''helper to sort by the attributes named by strings of attrs in order'''
      return lambda k: [ getattr(k, attr) for attr in attrs ]
    

    then to use it

    # would defined elsewhere but showing here for consiseness
    self.SortListA = ['attrA', 'attrB']
    self.SortListB = ['attrC', 'attrA']
    records = .... #list of my objects to sort
    records.sort(key=self.attr_sort(attrs=self.SortListA))
    # perhaps later nearby or in another function
    more_records = .... #another list
    more_records.sort(key=self.attr_sort(attrs=self.SortListB))
    

    This will use the generated lambda function sort the list by object.attrA and then object.attrB assuming object has a getter corresponding to the string names provided. And the second case would sort by object.attrC then object.attrA.

    This also allows you to potentially expose outward sorting choices to be shared alike by a consumer, a unit test, or for them to perhaps tell you how they want sorting done for some operation in your api by only have to give you a list and not coupling them to your back end implementation.

提交回复
热议问题