avatar
avatar

Reputation: 9

Sorting tuple list based on another list?

There are two lists.

list1 = [('ST00003', '009830'), ('ST00003', '005490'), ('ST00003', '005830'), ('ST00003', '251270'), ('ST00002', '111710')]
list2 = ['111710', '005830', '009830', '005490', '251270']


I want to sort list1 in order of list2.

list3 = [('ST00002', '111710'), ('ST00003', '005830'), ('ST00003', '009830'), ('ST00003', '005490'), ('ST00003', '251270')]

I want to make it like list3 when it's sorted. Is there any good way?

Upvotes: 0

Views: 41

Answers (3)

Aaj Kaal
Aaj Kaal

Reputation: 1274

Since second element of tuple is key used to sort, reverse the tuples and create a dict and use it for lookup. Minor assumption: This code will only produce correct results if the number of elements in the list1 and list2 are same.

Code:

list1 = [('ST00003', '009830'), ('ST00003', '005490'), ('ST00003', '005830'), ('ST00003', '251270'), ('ST00002', '111710')]
list2 = ['111710', '005830', '009830', '005490', '251270']

# desired list3 = [('ST00002', '111710'), ('ST00003', '005830'), ('ST00003', '009830'), ('ST00003', '005490'), ('ST00003', '251270')]
list1_rev_tuples = [(ele[1], ele[0]) for ele in list1]
dct = dict(list1_rev_tuples)
print(dct)
list3 = [(dct[ele], ele) for ele in list2]
print(list3)

Output:

{'009830': 'ST00003', '005490': 'ST00003', '005830': 'ST00003', '251270': 'ST00003', '111710': 'ST00002'}
[('ST00002', '111710'), ('ST00003', '005830'), ('ST00003', '009830'), ('ST00003', '005490'), ('ST00003', '251270')]

Upvotes: 0

superb rain
superb rain

Reputation: 5520

With a dict to look up the items:

>>> [*map({i[1]: i for i in list1}.get, list2)]
[('ST00002', '111710'), ('ST00003', '005830'), ('ST00003', '009830'), ('ST00003', '005490'), ('ST00003', '251270')]

(I'm assuming that you didn't provide a bad example, i.e., that if your real data isn't such a 1-to-1 correspondence between list1 and list2, you would'n't have made it look like it is.)

Upvotes: 0

quamrana
quamrana

Reputation: 39354

I did it my making an intermediate dict which maps from the number field to the index in list2:

list1 = [('ST00003', '009830'), ('ST00003', '005490'), ('ST00003', '005830'), ('ST00003', '251270'), ('ST00002', '111710')]
list2 = ['111710', '005830', '009830', '005490', '251270']

map2 = {value:index for index,value in enumerate(list2)}
print(map2)

list3 = sorted(list1, key = lambda i: map2[i[1]])
print(list3)

Output as required.

Upvotes: 2

Related Questions