python sorting two lists

前端 未结 3 1086
逝去的感伤
逝去的感伤 2020-12-15 17:42

I am trying to sort two lists together:

list1 = [1, 2, 5, 4, 4, 3, 6]
list2 = [3, 2, 1, 2, 1, 7, 8]

list1, list2 = (list(x) for x in zip(*sorted(zip(list1,          


        
3条回答
  •  再見小時候
    2020-12-15 18:15

    The trick here is that when Python does tuple comparisons, it compares the elements in order from left to right (for example, (4, 1) < (4, 2), which is the reason that you don't get the ordering you want in your particular case). That means you need to pass in a key argument to the sorted function that tells it to only use the first element of the pair tuple as its sort expression, rather than the entire tuple.

    This is guaranteed to retain the ordering you want because:

    sorts are guaranteed to be stable. That means that when multiple records have the same key, their original order is preserved.

    (source)

    >>> list1 = [1, 2, 5, 4, 4, 3, 6]
    >>> list2 = [3, 2, 1, 2, 1, 7, 8]
    >>> 
    >>> list1, list2 = (list(x) for x in zip(*sorted(zip(list1, list2), key=lambda pair: pair[0])))
    >>> 
    >>> print list1
    [1, 2, 3, 4, 4, 5, 6]
    >>> print list2
    [3, 2, 7, 2, 1, 1, 8]
    

提交回复
热议问题