Sort a list of lists with a custom compare function

后端 未结 4 2030
一向
一向 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:12

    Also, your compare function is incorrect. It needs to return -1, 0, or 1, not a boolean as you have it. The correct compare function would be:

    def compare(item1, item2):
        if fitness(item1) < fitness(item2):
            return -1
        elif fitness(item1) > fitness(item2):
            return 1
        else:
            return 0
    
    # Calling
    list.sort(key=compare)
    

提交回复
热议问题