简体   繁体   English

如何在 Python 中对字符串列表进行排序

[英]How to sort a list of strings in Python

In Python I have a list of str with this notation:Python中,我有一个带有以下符号的str列表:

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.使用sortedkey=参数(或list.sort() ),我们可以定义一个函数,用冒号分割每个项目并将部分转换为整数。 After that, Python's natural sorting does the rest of the work.之后,Python 的自然排序会完成剩下的工作。 (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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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