同时遍历两个列表的 pythonic 方式是什么?
假设我想逐行比较两个文件(将一个文件中的每个 i
行与另一个文件的第 i
行进行比较),我想要做这样的事情:
file1 = csv.reader(open(filename1),...)
file2 = csv.reader(open(filename2),...)
for line1 in file1 and line2 in file2: #pseudo-code!
if line1 != line2:
print "files are not identical"
break
实现这一目标的 pythonic 方法是什么?
编辑:我没有使用文件处理程序,而是使用 CSV 阅读器(csv.reader(open(file),...)
)和 zip()
似乎无法使用它...
最终编辑:就像@Alex M. 建议的那样,zip()
在第一次迭代时将文件加载到内存中,因此对于大文件来说这是一个问题。在 Python 2 上,使用 itertools
解决了这个问题。
最佳答案
在 Python 2 中,你应该导入 itertools并使用它的 izip :
with open(file1) as f1:
with open(file2) as f2:
for line1, line2 in itertools.izip(f1, f2):
if line1 != line2:
print 'files are different'
break
使用内置的 zip
,两个文件将在循环开始时立即全部读入内存,这可能不是您想要的。在 Python 3 中,内置的 zip
的工作方式类似于 itertools.izip
在 Python 2 中的工作方式——递增。
关于Python 双重迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2393444/