Python: sort an array of dictionaries with custom comparator?

后端 未结 8 1249

I have the following Python array of dictionaries:

myarr = [ { \'name\': \'Richard\', \'rank\': 1 },
{ \'name\': \'Reuben\', \'rank\': 4 },
{ \'name\': \'Reece\'         


        
8条回答
  •  时光取名叫无心
    2021-02-08 10:55

    I'm more leaning toward creating a compare function to handle the "0" specifically:

    def compare(x,y):
        if x == y:
            return 0
        elif x == 0:
            return 1
        elif y == 0:
            return -1
        else:
            return cmp(x,y)
    
    sorted(myarr, cmp=lambda x,y: compare(x,y), key=lambda x:x['rank'])
    

    However, there are performance penalty on the custom compare function.

提交回复
热议问题