首页 > 解决方案 > 如何对中间有浮点数的字符串列表进行排序?

问题描述

我需要根据字符串中间的浮点值对字符串列表进行排序。

我已经看到一些答案得到了 key keys.sort(key=float),但是在这些答案中,它们只有列表中的浮点数。在这种情况下,我需要将该字符串转换为浮点数并根据该值对其进行排序。最后,我将需要整个字符串。

list_of_msg = []
msg1 = "buy.apple<100; 21.15; Jonh>"
msg2 = "buy.apple<100; 20.00; Jane>"
msg3 = "buy.apple<50; 20.10; Anne>"
list_of_msg.append(msg1)
list_of_msg.append(msg2)
list_of_msg.append(msg3)
# sort method goes here
print(list_of_msg)

预计这将根据值 21.15、20.00、20.10 进行排序

 ['buy.apple<100; 20.00; Jane>', 'buy.apple<50; 20.10; Anne>', 
 'buy.apple<100; 21.15; Jonh']

标签: pythonstringsortingfloating-pointdouble

解决方案


使用sorted/sortkey参数:

sorted(list_of_msg, key=lambda x: float(x.split(';')[1].strip()))

我们基于原始列表中的元素进行拆分,并采用作为参数';'传递的第二次拆分。key


推荐阅读