python - 如何对中间有浮点数的字符串列表进行排序?
问题描述
我需要根据字符串中间的浮点值对字符串列表进行排序。
我已经看到一些答案得到了 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']
解决方案
使用sorted
/sort
带key
参数:
sorted(list_of_msg, key=lambda x: float(x.split(';')[1].strip()))
我们基于原始列表中的元素进行拆分,并采用作为参数';'
传递的第二次拆分。key
推荐阅读
- jenkins - jenkins作业执行后删除TFS工作区映射
- c++ - 如何将命令行参数转换为 int?
- javascript - 如何使用与 SMTP 凭据不同的域成功发送邮件?
- python - Python如何展平json文件,如json_normalize
- python - 如何能够导入谷歌驱动器文件夹中的每个文件?
- reactjs - React 项目结构的最佳实践?
- python - 使用 Blender API 保存 .3ds 或 .obj 文件
- hyperledger-fabric - Fabric make error etcd:不包含包 go.etcd.io/etcd/etcdserver/api/snap
- reactjs - 在没有外部依赖的情况下反应本机去抖钩子
- c# - 带有 id 的 ASP.NET WebAPI 2 版本控制 POST