python sorting two lists

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

    In you code the sorting is performed basing on the first and the second elements of the tuples, so the resulting second list elements are in the sorted order for the same elements of the first list.

    To avoid sorting based on the second list, just specify that only the elements from the first list should be used in the comparison of the tuples:

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

    itemgetter(0) takes the first element from each tuple, which belongs to the first list.

提交回复
热议问题