Marcelle Guedes
Marcelle Guedes

Reputation: 1

Sort criterion for 2 lists

I have two lists:

a = [2,3,1,4]
b=[two, three, one, four] 

I need to sort the first list in ascending order, but I need the second list ( made up of strings) to follow the same sorting. That is, I expect to get the following result:

a = [1,2,3,4]
b = [one, two, three, four]

does anyone have a simple way to do this?

Upvotes: 0

Views: 37

Answers (3)

Sean Suchter
Sean Suchter

Reputation: 338

aa, bb = zip(*sorted(zip(a, b)))

BTW, you will need to quote the items in the second list, unless those are variable references.

The inner zip puts the two lists together into one tuple:

[(2, 'two'), (3, 'three'), (1, 'one'), (4, 'four')]

The sorted does the sort. Tuples sort by their first key:

[(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]

The outer zip & * operator usage is an "unzip a list" pythonic trick.

Upvotes: 2

jay.cs
jay.cs

Reputation: 303

Use: sorted(zip(a,b))

We are basically zipping the two lists together. They need to have same length.

Upvotes: 1

John Gordon
John Gordon

Reputation: 33359

Combine the two lists into a list of two-element tuples and sort it:

mylist = [
    (2, "two"),
    (3, "three"),
    (1, "one"),
    (4, "four")
]
mylist.sort()

It will be sorted in order of the first element.

Upvotes: 0

Related Questions