How does a Python custom comparator work?

前端 未结 4 1521
甜味超标
甜味超标 2021-01-06 19:52

I have the following Python dict:

[(2, [3, 4, 5]), (3, [1, 0, 0, 0, 1]), (4, [-1]), (10, [1, 2, 3])]

Now I want to sort them on the basis o

4条回答
  •  迷失自我
    2021-01-06 20:44

    First, the cmp() function:

    cmp(...)
        cmp(x, y) -> integer
        Return negative if xy.
    

    You are using this line: items.sort(myComparator) which is equivalent to saying: items.sort(-1) or items.sort(0) or items.sort(1)

    Since you want to sort based on the sum of each tuples list, you could do this:

    mylist = [(2, [3, 4, 5]), (3, [1, 0, 0, 0, 1]), (4, [-1]), (10, [1, 2, 3])]
    sorted(mylist, key=lambda pair: sum(pair[1]))
    

    What this is doing is, I think, exactly what you wanted. Sorting mylist based on the sum() of each tuples list

提交回复
热议问题