Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Position words in a list based on occurences

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']

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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')]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading