-3

I cannot find an answer elsewhere on this site, which is why I am asking. My answer is different as it contains alpha-numeric values and will not work with any integer based solution here is a sample of my string:

01768
01785
01799
01804
01818
01821
01835
01849
01852
01866
XXXXX

What can i do to sort these in ascending/descending order, so far i have tried sorted() as it is used for stings, the output of this is ['0', '1', '6', '6', '8'] ['X', 'X', 'X', 'X', 'X']. i want each separate value to be ordered and not individual characters. Any help is appreciated.

EcSync
  • 842
  • 1
  • 6
  • 20
  • after sorting join them with empty string `''` – shaik moeed Feb 06 '19 at 07:22
  • @davedwards its not...this does not include enitrely integers, also contains `XXXXX` values...please read the question – EcSync Feb 06 '19 at 07:38
  • change your list or whatever this is to some python object for people to copy into their python ide. otherweise we don't know if your elments should be integers, strings or whatever object you might think of. – Florian H Feb 06 '19 at 07:41

3 Answers3

1

If you want to sort all these strings by their integer value then you can do this :

sorted(arr,key=lambda x:int(x))

Where arr is the list of all those strings.

Anonymous
  • 335
  • 1
  • 2
  • 17
1

Using sorted

Ex:

s = """01768
01785
01799
01804
01818
01821
01835
01849
01852
01866"""

print("Ascending")
print( "\n".join(map(str, sorted(map(int, s.splitlines())))) )
print("---")
print("Descending")
print( "\n".join(map(str, sorted(map(int, s.splitlines()), reverse=True))) )

Output:

Ascending
1768
1785
1799
1804
1818
1821
1835
1849
1852
1866
---
Descending
1866
1852
1849
1835
1821
1818
1804
1799
1785
1768
Rakesh
  • 81,458
  • 17
  • 76
  • 113
  • thanks for the response, however when i run this it makes no difference to the output, perhaps it is to do with my `XXXXX` values? – EcSync Feb 06 '19 at 10:13
1

Using this answer as a guide Does Python have a built in function for string natural sort?

alist = ['01768',
'01785',
'01799',
'01804',
'01818',
'01821',
'01835',
'01849',
'01852',
'01866',
'XXXXX']

from natsort import natsorted, ns
r = natsorted(alist, key=lambda y: y.lower())

>>>print(r)
['01768', '01785', '01799', '01804', '01818', '01821', '01835', '01849', '01852', '01866', 'XXXXX']
  • Are you sure this is the correct import? I have pip installed correctly however it cannot find `natsorted` i tried `import natsort` on its own, along with `r = natsort(etc)` but natsort is not callable – EcSync Feb 06 '19 at 08:20
  • 1
    Sorry yes `natsort` is not a built-in it needs to be installed by with `pip` or `python -m pip install natsort` – chickity china chinese chicken Feb 06 '19 at 08:24