0
a = [
    'suit1.png',
    'suit10.png',
    'suit2.png',
    'suit12.png',
    'suit3.png',
    'suit4.png',
    'suit5.png',
    'suit6.png',
    'suit7.png',
    'suit8.png',
]

sorted(a), sorts items in same way as seen in a list a.sort() also sort list in that way. Is it possible that 'suit10.png' and 'suit12.png' go on the end of list?

Alexander
  • 59,041
  • 12
  • 98
  • 151
agronom
  • 11
  • 1
  • Hi Agronom, I've found an exact match question. I've marked this one as a duplicate to point future readers to the duplicate. Let me know if the duplicate doesn't fully answer your question, and I'll reopen this one. – Alexander Aug 15 '21 at 18:05
  • 1
    @hansolo That's really brittle. There's better built-in solutions, see the dupe – Alexander Aug 15 '21 at 18:05
  • Hi, this is impossible to use sorted to achieve what you need. You will need some kind of natural sorting. You can use natsort to achieve this. The following code will do what you need: ``` from natsort import natsorted a = ['suit1.png', 'suit10.png', 'suit2.png','suit12.png','suit3.png', 'suit4.png', 'suit5.png', 'suit6.png', 'suit7.png', 'suit8.png'] print(natsorted(a)) ``` – vdmclcv Aug 15 '21 at 18:09

2 Answers2

1

Use custom sort as follows:

from functools import cmp_to_key

def cmp_items(a, b):
    if int(a.split('suit')[1].split('.png')[0]) > int(b.split('suit')[1].split('.png')[0]):
        return 1
    elif int(a.split('suit')[1].split('.png')[0]) == int(b.split('suit')[1].split('.png')[0]):
        return 0
    else:
        return -1

cmp_key = cmp_to_key(cmp_items)


a = [
    'suit1.png',
    'suit10.png',
    'suit2.png',
    'suit12.png',
    'suit3.png',
    'suit4.png',
    'suit5.png',
    'suit6.png',
    'suit7.png',
    'suit8.png',
]

a.sort(key = cmp_key)

print(a)
Deepak Tatyaji Ahire
  • 4,883
  • 2
  • 13
  • 35
0

Both the sorted function and the list.sort method take an optional key argument which dictates how items are to be sorted. Its value is to be a function that takes a member of the list as an argument and returns a value (usually a number). If a and b are elements of the list, then a will be placed before b if func(a) < func(b).

So, in this case, you could do

a.sort(key=lambda x : int(x[4:].split('.')[0]))
Daniel Walker
  • 6,380
  • 5
  • 22
  • 45