简体   繁体   中英

How to sort a list of strings in Python

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', ...]

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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM