且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python:不按字典顺序对字符串数字进行排序

更新时间:2023-02-19 12:52:54

您可以使用内置的 sorted() 函数和键 int 来映射每个项目在比较之前将列表中的整数转换为整数:

You can use the built-in sorted() function with a key int to map each item in your list to an integer prior to comparison:

numbers = ['10', '8', '918', '101010']
numbers = sorted(numbers, key=int)
print(numbers)

输出

['8', '10', '918', '101010']

使用此方法将根据需要输出字符串列表.

Using this method will output a list of strings as desired.