Sorting a List of Elements by the First element but if Equal sort by the second

前端 未结 1 1473
醉酒成梦
醉酒成梦 2020-12-30 11:45

I have constructed a list [[13, \"b\"], [10, \"b\"], [10, \"a\",], [4,\"c\"], [1, \"d\"]] which is sorted by the first value in the list of two elements. That

相关标签:
1条回答
  • 2020-12-30 12:12

    This works:

    >>> li=[[13, "b"], [10, "b"], [10, "a",], [4,"c"], [1, "d"]]
    >>> sorted(li,key=lambda sl: (-sl[0],sl[1]))
    [[13, 'b'], [10, 'a'], [10, 'b'], [4, 'c'], [1, 'd']]
    

    The sorted function produces a new list. You can also sort the list in place using the sort method:

    >>> li=[[13, "b"], [10, "b"], [10, "a",], [4,"c"], [1, "d"]]
    >>> li.sort(key=lambda sl: (-sl[0],sl[1]))
    >>> li
    [[13, 'b'], [10, 'a'], [10, 'b'], [4, 'c'], [1, 'd']]
    

    You can also do a nested sort (or sort on one key, then the second key) since python uses a stable sort:

    >>> from operator import itemgetter
    >>> li=[[13, "b"], [10, "b"], [10, "a",], [4,"c"], [1, "d"]]
    >>> li.sort(key=itemgetter(1))
    >>> li
    [[10, 'a'], [13, 'b'], [10, 'b'], [4, 'c'], [1, 'd']]
    >>> li.sort(key=itemgetter(0),reverse=True)
    >>> li
    [[13, 'b'], [10, 'a'], [10, 'b'], [4, 'c'], [1, 'd']]
    

    Since there is no need for a lambda in a one element sort, I used the faster operator.itemgetter vs a lambda. Whether two faster sorts are faster than one, I don't know... You can also use a lambda for this method.

    There is a great sort tutorial that shows many of these idioms.

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