我正在尝试对包含数字的字符串列表进行排序
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
我正在尝试对包含数字的字符串列表进行排序
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
您想根据float
值(不是字符串值)进行排序,因此请尝试:
>>> b = ["949.0","1099.0"]
>>> b.sort(key=float)
>>> b
['949.0', '1099.0']
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
如果有人在处理数字和扩展名,例如 0.png、1.png、10.png、2.png... 我们需要在扩展名之前检索和排序字符,因为这个扩展名不允许我们转换浮动名称:
myList = sorted(myList, key=lambda x: float(x[:-4]))
将它们转换为int
或float
什至decimal
(因为它有尾随数字)
>>> b = [float(x) for x in b]
>>> b.sort()
>>> b
[949.0, 1099.0]