gpt4 book ai didi

python - 有没有办法在 python 中简化这个 "n-way merge"

转载 作者:太空狗 更新时间:2023-10-30 02:28:34 24 4
gpt4 key购买 nike

所以现在我已经硬编码了 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com