2 回答
TA贡献1830条经验 获得超3个赞
这似乎有效:
from itertools import product
def _CabFare(x,y,z):
with open(x, 'r') as f, open(y, 'r') as g, open(z, 'wb') as h:
writer = csv.writer(h)
for row_a, row_b in product(csv.reader(f), csv.reader(g)):
if _ManhattanDistance(row_a, row_b) > 0:
writer.writerow(row_a)
writer.writerow(row_b)
速度较慢,但内存占用较少:
def _CabFare(x,y,z):
with open(x, 'r') as f, open(z, 'wb') as h:
writer = csv.writer(h)
for row_a in csv.reader(f):
with open(y, 'r') as g:
for row_b in csv.reader(g):
if _ManhattanDistance(row_a, row_b) > 0:
writer.writerow(row_a)
writer.writerow(row_b)
TA贡献1830条经验 获得超9个赞
reader是一个有状态的迭代器。一旦你用尽它,它就完成了,你需要重新打开它才能再次迭代文件:
def _CabFare(x,y,z):
with open(x, 'r') as f:
with open(y, 'r') as g:
with open(z, 'wb') as h:
reader_2 = csv.reader(g)
writer = csv.writer(h)
for row_b in reader_2:
reader_1 = csv.reader(f) # Reopen reader_1 for each iteration
for row_a in reader_1:
if _ManhattanDistance(row_a,row_b) > 0:
writer.writerow(row_a)
writer.writerow(row_b)
添加回答
举报