-2

Note: I understand this looks similar to a lot of questions, but wait just a second and finish reading.

Is there a way to sort a list by another where we do not have to merge the lists somehow?

items = ["a", "b", "c", "d", "e"]
minutes_ago = [1, 3, 2, 5, 4]

Result should be that the items are sorted by the minutes_ago list. What's the optimised way to do so?

I was thinking of some sorted(items, key = lambda ... ) but then couldn't imagine how to solve it nicely.

Out:

items = ["a", "c", "b", "e", "d"]
PascalVKooten
  • 20,643
  • 17
  • 103
  • 160
  • Why don't you want to merge them? (and then unmerge them after) – RemcoGerlich Nov 09 '14 at 21:23
  • Performance reasons. I cannot believe that the best we can do in python is to merge the lists. – PascalVKooten Nov 09 '14 at 21:25
  • Well you have to have *some* data structure that relates the items of the first list to the items of the other, that works in a sorting algorithm, that just tries to compare item. A list of tuples is a pretty natural way to do that. – RemcoGerlich Nov 09 '14 at 21:27
  • I agree, but in this case I really don't need them to be merged, and I'm only interested in "items" as output. I guess `zip` is the simple answer though. – PascalVKooten Nov 09 '14 at 21:29
  • Fair enough. Even though I came from a different perspective, the current best answer was also given on the simpler question "how to sort a list by another". Duplicate it is. – PascalVKooten Nov 09 '14 at 21:31
  • Another option would be to create an index list: `ndx = range(len(items)); print([items[n] for n in sorted(ndx, key=lambda x: minutes_ago[x])])` – Simon Nov 09 '14 at 21:38

1 Answers1

3

This is the simplest way I can think of:

In [1]: items = ["a", "b", "c", "d", "e"]

In [2]: minutes_ago = [1, 3, 2, 5, 4]

In [3]: [i for m, i in sorted(zip(minutes_ago, items))]
Out[3]: ['a', 'c', 'b', 'e', 'd']
Wolph
  • 78,177
  • 11
  • 137
  • 148