Python双迭代

2024-05-16 06:03:31 发布

您现在位置:Python中文网/ 问答频道 /正文

在两个列表上同时迭代的python方法是什么?

假设我想逐行比较两个文件(将一个文件的第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

什么是达到这个目的的Python方法?


编辑:我没有使用文件处理程序,而是使用CSV读取器(csv.reader(open(file),...)),而且zip()似乎无法使用它。。。


最终编辑:就像@Alex M.建议的那样,zip()在第一次迭代时将文件加载到内存中,因此对于大文件这是一个问题。在Python 2上,使用itertools可以解决这个问题。


Tags: 文件csv方法in编辑列表openzip
3条回答

在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,两个文件在循环开始时都将一次完全读入内存,这可能不是您想要的。在Python3中,内置的zip的工作方式与Python2中的itertools.izip类似——递增。

在锁定步骤中(对于Python≥3):

for line1, line2 in zip(file1, file2):
   # etc.

作为“二维阵列”:

for line1 in file1:
   for line2 in file2:
     # etc.
   # you may need to rewind file2 to the beginning.

我投票赞成使用zipmanual建议“同时循环两个或多个序列,条目可以与zip()函数配对”

例如

list_one = ['nachos', 'sandwich', 'name']
list_two = ['nachos', 'sandwich', 'the game']
for one, two in zip(list_one, list_two):
   if one != two:
      print "Difference found"

相关问题 更多 >