I have following list (A) of words: ['jack', 'steve', 'john', 'mary']
and its position in a sentence as a list (B): [0, 12, 3, 5]
That means in a ‘jack’ occurs at position 0 at a sentence, ‘steve’ at position 12, and so on.
How can I reorder list (A) so that the output is: ['jack', 'john', 'mary', 'steve']
Thank you for any help.
>Solution :
You can sort tuples with 2 values (as sort functions only look at the first value), then remove the other value with a list comprehension:
a = [x for _, x in sorted(zip(b, a))]
>>> a
['jack', 'john', 'mary', 'steve']
Sorting list based on values from another list
sorted()Python docs
As you can see:
>>> x = [(2, 'a'), (1, 'b')]
>>> x.sort()
>>> x
[(1, 'b'), (2, 'a')]