0

I have a range of Salaries in a list in Python sth like this ['10,000-15,0000','2,500'-'3,000','5,000-7,500'].

I would like to sort this list asc but if try list.sort() it doesnt sort the proper away because the objects in list are strings.Ι cant convert to int and sort because
of the '-'

  • Does this answer your question? [Python list sort in descending order](https://stackoverflow.com/questions/4183506/python-list-sort-in-descending-order) – Fabio Lopez Mar 30 '21 at 20:40
  • What have you tried so far? – alec_djinn Mar 30 '21 at 20:40
  • 1
    Please repeat [on topic](https://stackoverflow.com/help/on-topic) and [how to ask](https://stackoverflow.com/help/how-to-ask) from the [intro tour](https://stackoverflow.com/tour). In particular, you have to define your problem. You haven't specified what ordering you intend to impose on ranges, which do not have a natural ordering. You also list an inconsistent string format; processing these into range notation of some sort will be your first task. – Prune Mar 30 '21 at 20:40
  • there is a sort function You can use. see more here: https://www.programiz.com/python-programming/methods/list/sort – Matiiss Mar 30 '21 at 20:40
  • "I would like to sort this list but i cant find the proper way." What happened when you tried using any way at all? Exactly what result do you want for this input, and why (what is the rule that tells you which element goes before what)? – Karl Knechtel Mar 30 '21 at 20:41

2 Answers2

1

It's just a matter of using a sort key that turns the first half of the string into an integer.

lst = ['10,000-15,0000','2,500-3,000','5,000-7,500']
lst.sort( key=lambda x: int(x.split('-')[0].replace(',','')))
print(lst)

Output:

C:\Data>python x.py
['2,500-3,000', '5,000-7,500', '10,000-15,0000']

C:\Data>
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
  • Thank you very much Tim , this works for me , i am new to python and not used to lamba – Kleanthis Mpampotsi Mar 30 '21 at 20:47
  • IF you find it more understandable, you CAN move that into a standalone function, and pass the function name as the `key`. It works exactly the same. We Python nerds take too much pleasure into turning every problem into a one-liner. – Tim Roberts Mar 30 '21 at 21:43
0

Main thing ['10,000-15,0000','2,500'-'3,000','5,000-7,500'] this gives you an error... But.. eg: arr = ['10000-15000','16000-20000','2500-3000'] #this can be sorted using below line arr = sorted(arr)