作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
所以现在我已经硬编码了 4 个 if/elif/else 语句。有没有更动态的方法来做到这一点?例如,如果我想进行 10 路或 40 路合并?
#4-way merge sort, sorted page files
outfile="fullsorted.txt"
of=open(outfile,"w")
f1=open("temp0-sorted.txt","r")
f2=open("temp1-sorted.txt","r")
f3=open("temp2-sorted.txt","r")
f4=open("temp3-sorted.txt","r")
f1_line=f1.readline()
f2_line=f2.readline()
f3_line=f3.readline()
f4_line=f4.readline()
while len(f1_line)>0 and len(f2_line)>0 and len(f3_line)>0 and len(f4_line)>0:
if f1_line < f2_line and f1_line < f3_line and f1_line < f4_line and len(f1_line)>0:
of.write(f1_line)
f1_line=f1.readline()
elif f2_line < f3_line and f1_line < f4_line and len(f2_line)>0:
of.write(f2_line)
f2_line=f2.readline()
elif f3_line < f4_line and len(f3_line)>0:
of.write(f3_line)
f3_line=f3.readline()
else:
of.write(f4_line)
f4_line=f4.readline()
of.close()
最佳答案
只需使用 heapq.merge
:
import heapq
#4-way merge sort, sorted page files
outfile="fullsorted.txt"
with open("temp0-sorted.txt","r") as f1,\
open("temp1-sorted.txt","r") as f2,\
open("temp2-sorted.txt","r") as f3,\
open("temp3-sorted.txt","r") as f4,\
open(outfile,"w") as of:
of.writelines(heapq.merge(f1, f2, f3, f4))
关于python - 有没有办法在 python 中简化这个 "n-way merge",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36379360/
我是一名优秀的程序员,十分优秀!