如何对数字字符串的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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:18:37  来源:igfitidea点击:

How to sort python list of strings of numbers

python

提问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 bis sorting and not list a

但是列表b是排序而不是列表a

采纳答案by arshajii

You want to sort based on the floatvalues (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 intor floator even decimal(since it has trailing numbers)

将它们转换为intfloat甚至decimal(因为它有尾随数字)

>>> b = [float(x) for x in b]
>>> b.sort()
>>> b
[949.0, 1099.0]

回答by Samuele Mattiuzzo

use a lambdainside sort to convert them to float and then sort properly:

在 sort 中使用lambda将它们转换为浮点数,然后正确排序:

a = sorted(a, key=lambda x: float(x))

so you will mantain them as strings but sorted by value and not lexicographically

所以你会将它们保留为字符串,但按值排序而不是按字典序排序

回答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]))