首页 > 解决方案 > 如何根据第二个参数对输出文件进行排序?

问题描述

我正在尝试按字符后的整数对在某个字符“:”之后写入输出文件的结果进行排序。

首先,我尝试使用排序功能,但它没有工作,因为它不是一个列表。我还尝试将所有内容转换为字符串列表并尝试进行相应排序,但不认为这是最有效的方法。

注意:输出文件行都是字符串

**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!

谢谢您的帮助。

标签: python-3.xstringsortingoutputtext-files

解决方案


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

推荐阅读