Python sorting by multiple criteria

前端 未结 2 590
伪装坚强ぢ
伪装坚强ぢ 2020-11-30 11:01

I have a list where each element is of the form [list of integers, integer]. For example, an element of the list may look like this [[1,3,1,2], -1]

相关标签:
2条回答
  • 2020-11-30 11:25

    List the three criteria in your key:

    sorted(inputlist, key=lambda e: (len(e[0]), e[0], e[1]))
    

    Now you are sorting each element first by the length, then by comparing the first element directly (which in only used when the first element is of equal length), then by the value of the last integer.

    Python sorts tuples and lists like these lexicographically; compare the first element, and only if that doesn't differ, compare the second element, etc.

    The second element here is e[0] which will only be used if both compared entries have nested lists of equal length. These are again compared lexicographically, so pairing up elements until a pair differs.

    0 讨论(0)
  • 2020-11-30 11:42
    key = lambda x: (len(x[0]), x[0], x[1])
    

    This works because tuples (and lists) are compared by looking at each element in turn until a difference is found. So when you want to sort on multiple criteria in order of preference, just stick each criterion into an element of a tuple, in the same order.

    I'm assuming that by "smaller" you mean the same thing as "lesser", that is to say you don't mean to compare absolute values.

    0 讨论(0)
提交回复
热议问题