【问题标题】:How to sort a list of string that have float numbers in the middle?如何对中间有浮点数的字符串列表进行排序?
【发布时间】:2019-04-07 18:00:22
【问题描述】:

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

我已经看到一些答案获得了密钥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']

【问题讨论】:

    标签: python string sorting floating-point double


    【解决方案1】:

    sorted / sortkey 参数一起使用:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-04
      • 2011-03-26
      • 1970-01-01
      • 1970-01-01
      • 2021-12-21
      相关资源
      最近更新 更多