python sorting two lists

前端 未结 3 1083
逝去的感伤
逝去的感伤 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:11

    Use a key parameter for your sort that only compares the first element of the pair. Since Python's sort is stable, this guarantees that the order of the second elements will remain the same when the first elements are equal.

    >>> from operator import itemgetter
    >>> [list(x) for x in zip(*sorted(zip(list1, list2), key=itemgetter(0)))]
    [[1, 2, 3, 4, 4, 5, 6], [3, 2, 7, 2, 1, 1, 8]]
    

    Which is equivalent to:

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

提交回复
热议问题