-2

e.g.

lst1=['1.11','3.34','2.44','4.5']
lst2=['100.0','5000.9','999.0','666.0']

I want to sort the values in lst1 from max to min which I can do as follows:

lst1_sorted=sorted(lst1,key=float,reverse=True)

lst1_resorted = ['4', '3', '2', '1']

but then I also want to use the sorting on lst2 so that

lst2_resorted = ['666','5000','999','100']

This needs to work specifically for list entries which are floating point numbers. E.g. I can use key=float above. Ideally without having to import another library.

2one
  • 1,035
  • 3
  • 17
  • 36
  • 3
    `[b for a,b in sorted(zip(lst1, lst2),reverse=True)]` – Chris_Rands Jan 31 '19 at 16:01
  • Will this work with floating point numbers? – 2one Jan 31 '19 at 16:34
  • I did it like this: `xy=zip(x,y)` then: `xy.sort(key=lambda x: float(x[0]), reverse=True)` then: `y_resorted=list(zip(*xy)` where x is the list you want to sort on and y is the other list. – 2one Feb 01 '19 at 13:44
  • @2one Hello, I just wanted to know if my answer worked well for your problem :) – Federico Gentile Feb 18 '19 at 10:46
  • 1
    Yes but I was trying to avoid importing additional libraries so went with the method I mentioned in the comment above (Feb 1 at 13:44). Here have the points since you took the effort :) – 2one Feb 18 '19 at 13:15

2 Answers2

1

You can take advantage of the pandas library like so

import pandas as pd

# before
lst1=['1','3','2','4']
lst2=['100','5000','999','666']

# Use pandas
df = pd.DataFrame({'A':lst1,'B':lst2}).sort_values('A', ascending =False)

# After
lst1 = df['A'].tolist()
lst2 = df['B'].tolist()
Federico Gentile
  • 5,650
  • 10
  • 47
  • 102
0

You can use enumerate to calculate your indices, then index by them twice. Or, in fact, an arbitrary number of times.

from operator import itemgetter

idx = sorted(enumerate(lst1), key=lambda x: float(x[1]), reverse=True)
getter = itemgetter(*map(itemgetter(0), idx))

res1 = list(getter(lst1))  # ['4', '3', '2', '1']
res2 = list(getter(lst2))  # ['666', '5000', '999', '100']

For a one-off aligned sort, see Sorting list based on values from another list?

jpp
  • 159,742
  • 34
  • 281
  • 339