python Python双迭代
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2393444/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python double iteration
提问by Yuval Adam
What is the pythonic way of iterating simultaneously over two lists?
在两个列表上同时迭代的pythonic方法是什么?
Suppose I want to compare two files line by line (compare each i
th line in one file with the i
th line of the other file), I would want to do something like this:
假设我想逐行比较两个文件(将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
What is the pythonic way of achieving this?
实现这一目标的pythonic方法是什么?
Edit:I am not using a file handler but rather a CSV reader (csv.reader(open(file),...)
), and zip()
doesn't seem to work with it...
编辑:我没有使用文件处理程序,而是使用 CSV 阅读器 ( csv.reader(open(file),...)
),并且zip()
似乎无法使用它...
Final edit:like @Alex M. suggested, zip()
loads the files to memory on first iteration, so on big files this is an issue. On Python 2, using itertools
solves the issue.
最终编辑:就像@Alex M. 建议的那样,zip()
在第一次迭代时将文件加载到内存中,所以在大文件上这是一个问题。在 Python 2 上,使用itertools
解决了这个问题。
采纳答案by Alex Martelli
In Python 2, you should import itertoolsand use its izip:
在 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
with the built-in zip
, both files will be entirely read into memory at once at the start of the loop, which may not be what you want. In Python 3, the built-in zip
works like itertools.izip
does in Python 2 -- incrementally.
使用内置的zip
,这两个文件将在循环开始时立即完全读入内存,这可能不是您想要的。在 Python 3 中,内置的zip
工作方式与itertools.izip
Python 2 中的一样——增量式。
回答by JAL
I vote for using zip
. The manualsuggests "To loop over two or more sequences at the same time, the entries can be paired with the zip() function"
我投票赞成使用zip
. 该手册建议“要同时遍历两个或多个序列,这些条目可以与拉链()函数配对”
For example,
例如,
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"
回答by kennytm
In lockstep (for Python ≥3):
步调一致(对于 Python ≥3):
for line1, line2 in zip(file1, file2):
# etc.
As a "2D array":
作为“二维数组”:
for line1 in file1:
for line2 in file2:
# etc.
# you may need to rewind file2 to the beginning.