python-3.x - 如何根据第二个参数对输出文件进行排序?
问题描述
我正在尝试按字符后的整数对在某个字符“:”之后写入输出文件的结果进行排序。
首先,我尝试使用排序功能,但它没有工作,因为它不是一个列表。我还尝试将所有内容转换为字符串列表并尝试进行相应排序,但不认为这是最有效的方法。
注意:输出文件行都是字符串
**Current written output in output_file1.txt:**
hi: 011
hello: 000
hero: 001
You are done!
**Expected written output in output_file1.txt:**
hello: 000
hero: 001
hi: 011
You are done!
谢谢您的帮助。
解决方案
with open(filepath) as file:
r = file.readlines()
#splits based on ":" and then sort using the second value ie binary numbers
s = sorted([line.split(":") for line in r[1:-1]], key=lambda x: int(x[1]))
s.insert(0,r[0])
s.append(r[-1])
#Write 's' into File
推荐阅读
- java - 有没有办法使用 Regex 在 Mongo 上执行 indexOps?
- r - 使用类似名称的主文件重命名 Multi-FASTA 序列标题
- linux - 如何在 Linux Azure Function 启动命令上安装 libgdiplus apt 包?
- postgresql - WSL:如何将 postgres 添加到 ohmyzsh PATH
- sql - 如何从数据库中删除 SQLAlchemy 多对多孤儿?
- python - 如何在二维数组中查找特定元素?
- git - 如何从 git 的主分支中删除父级?
- angular - .subscribe(x=> ...) 和 .subscribe(next(...)) 之间的区别?
- laravel - 从数据透视表中显示刀片中的数据
- python - 将列表列表转换为字典字典