[英]merge two files sorted numerically by an integer in each line without reading into memory and without sorting
我有两个文件,file1和file2,按列2按数字排序:
文件1
A 1
B 10
文件2
C 2
D 100
我想合并它们并得到这个输出,它也按第2列数字排序:
D 1
B 2
C 10
A 100
我可以使用此unix命令来执行此操作,该命令不会排序,但会合并预先排序的文件:
sort -m -k2n,2 file1 file2
但是如何在没有将文件读入内存且没有排序的情况下在Python 3.4中执行此操作? Python 3.5将根据docs.python.org , bugs.python.org和github.com向heapq.merge()添加一个关键参数,但没有预发布版本可用。 与此同时,我想出了下面的解决方案。 有更优雅的方式吗? 我可以使用地图并循环播放这两个文件吗? 也许我应该发布到codereview呢?
import heapq
def key_generator(fd):
for line in fd:
yield int(line.split()[1]), line
with open('file1') as fd1, open('file2') as fd2:
it1 = key_generator(fd1)
it2 = key_generator(fd2)
for key, line in heapq.merge(it1, it2):
print(line, end='')
我刚刚下载了Python3.5的alpha版本1,我可以使用heapq.merge()的新关键函数来完成它:
from heapq import merge
def keyfunc(s):
return int(s.split()[1])
with open('file1') as fd1, open('file2') as fd2:
for line in merge(fd1, fd2, key=keyfunc):
print(line)
或者对于那些喜欢一行lambda函数的人:
key=lambda line: int(line.split()[1])
我可以使用map,operator.itemgetter(),str.split和int在一行中完成此操作吗?
你可以试试这种方式
dict={}
with open("a.txt",'r') as f1, open("b.txt",'rb') as f2:
lines_a=f1.readlines()
lines_b=f2.readlines()
for line in lines_a:
dict.update({line.split()[0]:int(line.split()[1])})
for line in lines_b:
dict.update({line.split()[0]:int(line.split()[1])})
for w in sorted(dict, key=dict.get):
print w,(dict[w])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.