-1

I have two lists

X = ["a", "b", "c", "d"]
Y = [3, 1, 5, 2]

and want to sort the list X to

X = ["c", "a", "d", "b"]

based on descending values of items in list Y in the corresponding positions

Mazdak
  • 105,000
  • 18
  • 159
  • 188
user2201609
  • 93
  • 4
  • 11
  • https://wiki.python.org/moin/HowTo/Sorting – Peter Wood Feb 29 '16 at 08:01
  • why don't you use dictionary, or do you really need to have two different lists. – Jay T. Feb 29 '16 at 08:04
  • You have an `index out of range`. Index 5 has no correspond item in `X`. – Avihoo Mamka Feb 29 '16 at 08:06
  • There's actually even simpler way than the accepted answer: `dict(zip(Y, X)).values()[::-1]` – martin Feb 29 '16 at 08:22
  • @Martin - dicts are unordered by definition, and so are the sequences (views) returned by `values()`, `keys()` or `items()`, any kind of ordering you see is due to the used hashing implementation and as such an imlementation detail. Never rely on the ordering of a dict (unless of a special dict imlememtation like OrderedDict) – mata Feb 29 '16 at 08:25

3 Answers3

2

Tuples, by default, are ordered by the first value.

So zip the lists with Y's items first, sort it (reversed) and then extract the second item (X):

>>> sorted_list = [item[1] for item in sorted(zip(Y, X), reverse=True)]
>>> sorted_list
['c', 'a', 'd', 'b']
>>>
Reut Sharabani
  • 30,449
  • 6
  • 70
  • 88
1

You can use a dictionary to keep the mapping and then do the sort:

>>> X
['a', 'b', 'c', 'd']

>>> Y
[3, 1, 5, 2]

>>> d = dict(zip(X, Y))

>>> sorted(X, key=lambda x: d[x], reverse=True)
['c', 'a', 'd', 'b']
heemayl
  • 39,294
  • 7
  • 70
  • 76
  • no problem... and just a small other hint: instead of a lambda you could use `key=d.get` (or `d.__getitem__`), but the general problem with this solution is that it does only work if there are no duplicate keys in `X`. – mata Feb 29 '16 at 08:21
  • @mata thanks.. i have learned a few things :) – heemayl Feb 29 '16 at 08:25
1
X = ["a", "b", "c", "d"]
Y = [3, 1, 5, 2]
zipped = zip(Y,X)
zipped.sort()
print zipped
[(1, 'b'), (2, 'd'), (3, 'a'), (5, 'c')]
HenryM
  • 5,557
  • 7
  • 49
  • 105
  • Might be worth to mention that in python3 `zip` doesn't return a list but a zip object wich doesn't have a `.sort()` method. `sorted(zip(Y, X))` would work in both python2 and python3. – mata Feb 29 '16 at 08:11