0

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.

gunardilin
  • 349
  • 3
  • 12

2 Answers2

4

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')]
Freddy Mcloughlan
  • 4,129
  • 1
  • 13
  • 29
  • In fact, it does not only look at the first value. It compares the first value first, if the first value of the two compared is the same, it will compare the second value. – Mechanic Pig Jun 05 '22 at 12:09
  • @MechanicPig, Thank you, I didn't know that. Does this apply if the 1st and 2nd are the same, will it keep going down until they are different? Is this in any documentation also? – Freddy Mcloughlan Jun 05 '22 at 23:01
  • 1
    Refer to https://stackoverflow.com/questions/5292303/how-does-tuple-comparison-work-in-python and https://docs.python.org/3/reference/expressions.html#comparisons – Mechanic Pig Jun 06 '22 at 01:19
3

You could create a dict and pass its get method as key parameter in sorted

>>> words = ['jack', 'steve', 'john', 'mary']
>>> pos = [0, 12, 3, 5]
>>> sorted(words, key=dict(zip(words, pos)).get)
['jack', 'john', 'mary', 'steve']

You could create the dict beforehand to make it more meaningful:

>>> word_pos = dict(zip(words, pos))
>>> sorted(words, key=word_pos.get)
['jack', 'john', 'mary', 'steve']

Another, slightly arcane way would be to use an iterator object and call the next function on it. But it may be a little confusing.

>>> words = ['jack', 'steve', 'john', 'mary']
>>> pos = [0, 12, 3, 5]
>>> it = iter(pos)
>>> sorted(words, key=lambda _: next(it))
['jack', 'john', 'mary', 'steve']
Sayandip Dutta
  • 15,602
  • 4
  • 23
  • 52