Home > Software design >  How to sort a list of strings in Python
How to sort a list of strings in Python

Time:05-24

In Python I have a list of str with this notation:

MyList = ['1:10', '5:2', '10:7', ...]

Where the characters before the : stand for the line number and the characters after it are the column number.
I would like to know if it is possible to sort the list like this:

MyList = ['1:1', '1:2', '1:3', ..., '2:1', '2:2', '2:3', ...]

CodePudding user response:

Sure. Using the key= argument to sorted (or list.sort()), we can define a function that splits each item by colon(s) and casts the parts to integers. After that, Python's natural sorting does the rest of the work. (Iterables such as lists are compared item-wise, and integers are compared as you would expect integers to be compared.)

>>> MyList = ['5:2', '1:10', '93:881', '93:8', '4:8', '10:7']
>>> sorted(MyList, key=lambda item: [int(part) for part in item.split(":")])
['1:10', '4:8', '5:2', '10:7', '93:8', '93:881']
  • Related