-1

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 duplicated elements.

list_a = [3,2,4,4,5]
list_b = ['d','b','a','c','b']

The output needs to be based on (1) the value from list_a from the largest to the smallest, and (2) for elements with the same value in list_a, sort by alphabetical order in list_b.

list_a = [5,4,4,3,2]
list_b = ['b','a','c','d','b']

Any ideas?

superb rain
  • 5,300
  • 2
  • 11
  • 25
ponderwonder
  • 127
  • 9

1 Answers1

2

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)
superb rain
  • 5,300
  • 2
  • 11
  • 25
  • It works well. I am still trying to understand the lambda part. Does p[0] refer to list_a and p[1] refer to list_b? What does the negative sign before p[0] mean? Thank you! – ponderwonder Sep 05 '20 at 11:15
  • 1
    Yes, `p` is a pair with a `list_a` element and the corresponding `list_b` element. The negation achieves descending order. – superb rain Sep 05 '20 at 11:18