Reputation: 35
How to reorder the first list based from another list in Python?
I cannot reorder the 2 list so here's my code:
import random
numElements1 = int(input("Enter the number of elements for first list: "))
numElements2 = int(input("Enter the number of elements for second list: "))
randomlist = random.sample(range(10, 99), numElements1)
print(randomlist)
randomlist2 = random.sample(range(10, 99), numElements2)
print(randomlist2)
Upvotes: 0
Views: 84
Reputation: 9061
You can use sorted()
with zip()
arr, index = map(list, zip(*sorted(zip(arr, index), key=lambda x: x[1])))
print(arr) #[40, 60, 90, 50, 70]
print(index) #[0, 1, 2, 3, 4]
Upvotes: 1
Reputation: 464
a={}
for i in index:
a[i]=randomlist[i]
for i,j in sorted(a.items()):
out_index.append(i)
out_arr.append(j)
Upvotes: 1