Python:不按字典顺序对字符串数字进行排序 [英] Python: sorting string numbers not lexicographically
本文介绍了Python:不按字典顺序对字符串数字进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串数字数组,例如:
I have an array of string-numbers, like:
numbers = ['10', '8', '918', '101010']
当我使用 sorted(numbers)
时,我会按字典顺序对它们进行排序,例如<代码>'8' >'17'.
When I use sorted(numbers)
, I get them sorted lexicographically, e.g. '8' > '17'
.
如何遍历根据数值排序的字符串?
How can I iterate over the strings sorted according to the number value?
推荐答案
您可以使用内置的 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.
这篇关于Python:不按字典顺序对字符串数字进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文