Sorting two arrays at once in Python

If two arrays should be sorted with the same criteria, use zip.

>>> x1 = ['c', 'a', 'b']
>>> y1 = [3, 1, 2]
>>> z = zip(x1, y1)
>>> z.sort()
>>> z
[('a', 1), ('b', 2), ('c', 3)]
>>> # Because zip returns tuples, we need to convert them to lists.
>>> x2, y2 = map(lambda x: list(x), zip(*z))
>>> x2
['a', 'b', 'c']
>>> y2
[1, 2, 3]

Similar Posts:

Comments 2

  1. cozy5f wrote:

    Suppose Python 2.

    map(lambda x: list(x), zip(*z)) could be map(list, zip(*z)).

    Even zip(*z) is sufficient if tuples are OK.

    Posted 05 Aug 2016 at 3:17 pm
  2. cozy5f wrote:

    Great, anyway!

    Posted 05 Aug 2016 at 3:34 pm

Post a Comment

Your email is never published nor shared.