Sort a list of lists with a custom compare function

后端 未结 4 2037
一向
一向 2020-12-07 15:22

I know there are several questions named like this, but they don\'t seem to work for me.

I have a list of lists, 50 times 5 elements. I want to sort this list by app

4条回答
  •  生来不讨喜
    2020-12-07 16:07

    >>> l = [list(range(i, i+4)) for i in range(10,1,-1)]
    >>> l
    [[10, 11, 12, 13], [9, 10, 11, 12], [8, 9, 10, 11], [7, 8, 9, 10], [6, 7, 8, 9], [5, 6, 7, 8], [4, 5, 6, 7], [3, 4, 5, 6], [2, 3, 4, 5]]
    >>> sorted(l, key=sum)
    [[2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7], [5, 6, 7, 8], [6, 7, 8, 9], [7, 8, 9, 10], [8, 9, 10, 11], [9, 10, 11, 12], [10, 11, 12, 13]]
    

    The above works. Are you doing something different?

    Notice that your key function is just sum; there's no need to write it explicitly.

提交回复
热议问题