0

I wrote simple list of elements then I sort it out but, the sorted list is:

lis = ["P1","P3","P4","P11","P22"]
lis.sort()
print(lis)

The output will be:

['P1', 'P11', 'P22', 'P3', 'P4']

but I would expected list:

['P1', 'P3', 'P4', 'P11', 'P22']

as the 11 and 22 are bigger than 3 and 4.

I know that it is string list but can I do it somehow?

martineau
  • 119,623
  • 25
  • 170
  • 301
  • 1
    Python sort functions take a key function. Make a function that turns your string into a number and pass it to `key=`. – Mark Aug 15 '21 at 18:53
  • 1
    Suggest you take a peek at the [Sorting HOW TO](https://docs.python.org/3/howto/sorting.html) in the fine documentation. – martineau Aug 15 '21 at 19:23

2 Answers2

2
lis = ["P1","P3","P4","P11","P22"]
lis.sort(key=lambda x: int(x.split('P')[-1]))
print(lis)

# ["P1","P3","P4","P11","P22"]
ShlomiF
  • 2,686
  • 1
  • 14
  • 19
0

If you know that all your strings have this same format of P followed by a number, then just remove the P and convert to int.

lis = ["P1","P3","P4","P11","P22"]
lis.sort(key=lambda x: int(x[1:]))
print(lis)

# ['P1', 'P3', 'P4', 'P11', 'P22']

If the more general case where you don't know the format of the strings, but want to sort using what is commonly referred to as natural sort, you can use module natsort:

import natsort
lis = ['Alice11C', 'Bob10', 'Alice2B', 'Bob9']
print(natsort.natsorted(lis))

# ['Alice2B', 'Alice11C', 'Bob9', 'Bob10']
Stef
  • 13,242
  • 2
  • 17
  • 28