Afzal
Afzal

Reputation: 189

Reorder list to match another

Say I have an array like:

[[1356, a], [478, b], [60, c], [61, d]]

Is it possible to reorder it to match with the array:

[d, b, a, c]

Like:

[[61,d], [478,b], [1356,a], [60,c]]

The order i want is in the second column of a csv file. So I have:

with open('data.csv', "r") as csvfile:
     order = csv.reader(csvfile, delimiter = ',')
     code_order=[]
     for row in order:
        code_order.append(row[2])
     reordered_output=[]
     for i,x  in enumerate(code_order):
          where x[i] in result
               reordered_ouput[i] = result
     print(reordered_output)

Upvotes: 2

Views: 103

Answers (1)

Bhargav Rao
Bhargav Rao

Reputation: 52081

One of the ways can be using sorted with a key

>>> a = [[1356, 'a'], [478, 'b'], [60, 'c'], [61, 'd']]
>>> b = ['d', 'b', 'a', 'c']
>>> sorted(a, key = lambda x : b.index(x[1]))
[[61, 'd'], [478, 'b'], [1356, 'a'], [60, 'c']]

Upvotes: 7

Related Questions