Python双迭代
在两个列表上同时迭代的Python方式是什么 假设我想逐行比较两个文件(将一个文件中的每个Python双迭代,python,Python,在两个列表上同时迭代的Python方式是什么 假设我想逐行比较两个文件(将一个文件中的每个Ith行与另一个文件的Ith行进行比较),我想做如下操作: file1 = csv.reader(open(filename1),...) file2 = csv.reader(open(filename2),...) for line1 in file1 and line2 in file2: #pseudo-code! if line1 != line2: print "fil
I
th行与另一个文件的I
th行进行比较),我想做如下操作:
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
什么是蟒蛇式的方法来实现这一点
编辑:我使用的不是文件处理程序,而是CSV阅读器(
CSV.reader(open(file),…)
),而zip()
似乎无法使用它
最终编辑:就像@Alex M.建议的那样,
zip()
在第一次迭代时将文件加载到内存中,因此对于大文件,这是一个问题。在Python2上,使用itertools
解决了这个问题。在lockstep中(对于Python≥3) :
作为“二维阵列”:
我投票赞成使用
zip
。建议“要同时循环两个或多个序列,条目可以与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"
在Python 2中,您应该导入并使用其:
使用内置的
zip
,两个文件将在循环开始时立即完全读入内存,这可能不是您想要的。在Python3中,内置的zip
与Python2中的itertools.izip
类似——以增量方式工作。谢谢,我正在寻找lockstep方法。你知道为什么这个方法不适用于csv.reader()
?也许你应该澄清一下,对于“2D数组”,你可能需要重新初始化内部迭代器…@Yuval,请编辑你的答案,以准确地显示你是如何尝试将zip与一个(一个?!)csv.reader一起使用的——这个注释是完全神秘的。这就完成了!事实上,问题是这些文件非常大,zip()
正在将它们全部加载到内存中……啊,也许这就是为什么我看不出有什么不同。我正在使用Python3.1。@KennyTM,是的,没有“可能”:在Python3中,过去依赖Python2中所有内存中列表的许多东西,现在都变成了增量和迭代的。因此,始终澄清问题和答案是与Python 2还是与Python 3相关是很重要的——在Python 2中(更好;-)增量和迭代方法可以说是“选择加入”(您需要显式地获得它),在Python 3中它是固有的(在相对罕见的情况下,您需要显式调用list
,实际需要一个列表,全部同时存储在内存中;-)。请注意:如果需要,您可以使用语句在同一中打开两个文件:将open(file1)作为f1,将open(file2)作为f2
:可能的重复
for line1 in file1:
for line2 in file2:
# etc.
# you may need to rewind file2 to the beginning.
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"
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