Home > Back-end >  Re-arranging lists
Re-arranging lists

Time:10-15

I have two lists, let's say listOne = ['a','b','c'] and listTwo = [['d'], ['e'], ['f']] and I also have a function MyFunction which takes listOne as a parameter and re-arranges it according to a bunch of conditions, then returns it.

So now I have listOne = ['b','a','c'], what I am trying to achieve here is I want listTwo also be arranged exactly how listOne got re-arranged.

So my listTwo would end up as listTwo = [['e'], ['d'], ['f']]

I know this can be achieved through loop or if statements but is there any built-in function or maybe a very efficient piece of code that can achieve this in a short amount of time without using a number of steps?

CodePudding user response:

If the values are unique, you can build a dictionary of mappings between listOne and listTwo before transforming listOne. then reorganize listTwo using the dictionary

mapping = dict(zip(listOne,listTwo))
listOne = myFunction(listOne)
listTwo = [mapping[n] for n in listOne]

Note that values un listOne must be hashable for this to work

You can even extend this to more lists with an extra zip:

mapping = dict(zip(listOne,zip(listTwo,listThree,listFour)))
listOne = myFunction(listOne)
listTwo,listThree,listFour = map(list,zip(*map(mapping.get,listOne)))

If listTwo is not yet available when you apply myFunction to listOne, you can hold indexes in your mapping dictionary instead of values. Then you can apply the indexes to listTwo (and any other lists) afterward:

indexMap  = {n:i for i,n in enumerate(listOne)}
listOne   = ['b','a','c'] #myFunction(listOne)
listTwo   = [listTwo[indexMap[n]] for n in listOne]

listThree = [listThree[indexMap[n]] for n in listOne]
listFour  = [listFour[indexMap[n]] for n in listOne]
  • Related