Reputation: 39
How can I link these two lists so when one list changes(the order) the other list follows keeping with the same numbers
List2=[5,4,3,2,1]
List3=[2,4,6,8,10]
changing the order of list2 and expected output
List2=[1,2,3,4,5]
List3=[10,8,6,4,2]
but the list2 order will change every time but always needs to be changed back to 1-5
(Python 3.6)
Upvotes: 0
Views: 430
Reputation: 18916
List2=[5,4,3,2,1]
List3=[2,4,6,8,10]
The "easier" way would be to make a dictionary of dict3 and use that after you remake list 2. Something like this:
# Pair the lists
List3 = dict(zip(List2,List3))
# Remake List2
List2 = sorted(List2)
# Remake List3 based on List2
List3 = [List3[key] for key in List2]
List3
Returns:
[10, 8, 6, 4, 2]
Upvotes: 0
Reputation: 402852
Define a small helper function to sort the two lists based on one of them.
def revert(a, b):
a, b = map(list, zip(*sorted(zip(a, b), key=lambda x: x[0])))
return a, b
Now, call this function as and when needed.
List2, List3 = revert(List2, List3)
Upvotes: 1