34

我正在尝试对包含数字的字符串列表进行排序

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']

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

4

4 回答 4

84

您想根据float值(不是字符串值)进行排序,因此请尝试:

>>> b = ["949.0","1099.0"]
>>> b.sort(key=float)
>>> b
['949.0', '1099.0']
于 2013-07-04T15:51:05.323 回答
20

use a lambda inside sort to convert them to float and then sort properly:

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

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

于 2013-07-04T15:52:16.497 回答
9

如果有人在处理数字和扩展名,例如 0.png、1.png、10.png、2.png... 我们需要在扩展名之前检索和排序字符,因为这个扩展名不允许我们转换浮动名称:

myList = sorted(myList, key=lambda x: float(x[:-4]))
于 2020-05-12T11:40:00.743 回答
3

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

>>> b = [float(x) for x in b]
>>> b.sort()
>>> b
[949.0, 1099.0]
于 2013-07-04T15:50:27.020 回答