How does a Python custom comparator work?

前端 未结 4 1523
甜味超标
甜味超标 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:29

    The number and which comparisons are done is not documented and in fact, it can freely change from different implementations. The only guarantee is that if the comparison function makes sense the method will sort the list.

    CPython uses the Timsort algorithm to sort lists, so what you see is the order in which that algorithm is performing the comparisons (if I'm not mistaken for very short lists Timsort just uses insertion sort)

    Python is not keeping track of "keys". It just calls your comparison function every time a comparison is made. So your function can be called many more than len(items) times.

    If you want to use keys you should use the key argument. In fact you could do:

    items.sort(key=lambda x: sum(x[1]))
    

    This will create the keys and then sort using the usual comparison operator on the keys. This is guaranteed to call the function passed by key only len(items) times.


    Given that your list is:

    [a,b,c,d]
    

    The sequence of comparisons you are seeing is:

    b < a   # -1  true   --> [b, a, c, d]
    c < b   # -1  true   --> [c, b, a, d]
    d < c   # 1   false
    d < b   # 1   false
    d < a   # -1  true   --> [c, b, d, a]
    

提交回复
热议问题