如何使用Python按数值和名称对文本文件数据进行排序
Python实现化合物分值排序方案
下面提供两种可直接使用的实现方式,默认输入文件为input.txt,排序后结果输出到sorted_output.txt。
原生Python实现(无需安装第三方依赖)
直接用Python内置方法即可完成需求,兼容性最好:
# 读取并解析数据 data = [] with open("input.txt", "r", encoding="utf-8") as f: for line in f: line = line.strip() if not line: # 跳过空行 continue # 按固定分隔符切分,支持化合物名含空格的场景 name_part, score_part = line.split(" score = ") score = float(score_part) data.append((score, name_part)) # 排序规则调整 # 1. 分值升序+同分按名称字典序升序:key=lambda x: (x[0], x[1]) # 2. 分值降序+同分按名称字典序升序:key=lambda x: (-x[0], x[1]) sorted_data = sorted(data, key=lambda x: (x[0], x[1])) # 写入输出文件 with open("sorted_output.txt", "w", encoding="utf-8") as f: for score, name in sorted_data: f.write(f"{name} score = {score}\n")
你可以根据自己的排序需求,修改sorted方法的key参数即可。
Pandas实现(适合后续需要进一步处理数据的场景)
如果已经安装了pandas包,代码会更简洁:
import pandas as pd # 读取数据 df = pd.read_csv("input.txt", sep=" score = ", engine="python", names=["compound_name", "score"]) # 排序规则调整,ascending参数对应两个字段的排序方向:True为升序,False为降序 # 示例为分值降序,同分按名称升序: df_sorted = df.sort_values(by=["score", "compound_name"], ascending=[False, True]) # 输出到文件 df_sorted.to_csv("sorted_output.txt", sep=" ", header=False, index=False, float_format="%.3f")
可根据需要调整ascending参数的取值,匹配你的排序要求。
内容的提问来源于stack exchange,提问作者keystothecity
相关产品推荐
相关产品推荐

