How to sort two lists based on one first and the other next in Python?

前端 未结 1 941
耶瑟儿~
耶瑟儿~ 2020-12-18 17:34

To sort two lists in parallel, what\'s the way of sorting by one list first, then for elements with the same value, sorting by the second list? Either list could have duplic

相关标签:
1条回答
  • 2020-12-18 18:08

    Pair, sort, unpair, write back:

    list_a[:], list_b[:] = zip(*sorted(zip(list_a, list_b), key=lambda p: (-p[0], p[1])))
    

    Writing back keeps it short and sorts the existing list objects rather than having separate new ones.

    More vertical version, probably nicer:

    pairs = list(zip(list_a, list_b))
    pairs.sort(key=lambda p: (-p[0], p[1]))
    list_a[:], list_b[:] = zip(*pairs)
    
    0 讨论(0)
提交回复
热议问题