如何对数字字符串的python列表进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17474211/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to sort python list of strings of numbers
提问by vaibhav jain
I am trying to sort list of strings containing numbers
我正在尝试对包含数字的字符串列表进行排序
a = ["1099.0","9049.0"]
a.sort()
a
['1099.0', '9049.0']
b = ["949.0","1099.0"]
b.sort()
b
['1099.0', '949.0']
a
['1099.0', '9049.0']
But list b
is sorting and not list a
但是列表b
是排序而不是列表a
采纳答案by arshajii
You want to sort based on the float
values (not string values), so try:
您想根据float
值(而不是字符串值)进行排序,请尝试:
>>> b = ["949.0","1099.0"]
>>> b.sort(key=float)
>>> b
['949.0', '1099.0']
回答by Markon
They are both sorted. '1' comes before '9'. Look at here: Ascii table
它们都是排序的。“1”在“9”之前。看这里: Ascii 表
回答by xlharambe
Convert them to int
or float
or even decimal
(since it has trailing numbers)
将它们转换为int
或float
甚至decimal
(因为它有尾随数字)
>>> b = [float(x) for x in b]
>>> b.sort()
>>> b
[949.0, 1099.0]
回答by Samuele Mattiuzzo
回答by Borja_042
In case anybody is dealing with numbers and extensions such as 0.png, 1.png, 10.png, 2.png... We need to retrieve and sort the characters before the extension since this extension does not let us to convert the names to floats:
如果有人正在处理数字和扩展名,例如 0.png、1.png、10.png、2.png...我们需要在扩展名之前检索和排序字符,因为这个扩展名不允许我们转换浮动名称:
sorted(list, key=lambda x: float(x[:-4]))