Python:如何做循环的嵌套枚举?

问题描述:

我有两个文件,file1file2,并且对于每个file1行,我试图检查所有行file2Python:如何做循环的嵌套枚举?

所以我做了循环嵌套枚举,但检查的file1第一线对抗file2所有行,该方案只是完成,而不是移动到下一行file1要检查的file2所有行。

以下是我有:

def testing(): 
    file1 = open(‘file1.txt’, 'r') 
    file2 = open(‘file2.txt’, 'r') 

    for index1, line1 in enumerate(file1): 
     for index2, line2 in enumerate(file2): 
       #    Here it prints the first line of `file1.txt` and after checking against all the lines of `file2.txt` (`for index2, line2 in enumerate(file2.txt)`) it completes, rather then going to the outer loop and proceed looping 
       print("THIS IS OUTER FOR LOOP LINE: " + line1 + " WITH LINE NUMBER: " + str(index1)) 

    file1.close() 
    file2.close() 

如何检查的file1反对file2所有行的每一行?我在这里做错了什么?

谢谢你提前一定会给予好评/接受的答案

+0

你可以使用'file2.readlines()'到第二个文件的内容加载到内存中,并遍历这些数据然后 – Felix

file2的位置推回到每个循环顶部的开始位置。无论是关闭并重新打开它作为aryamccarthy建议,或者简单地移动指针做的更清洁的方式:

file1 = open(‘file1.txt’, 'r') 
file2 = open(‘file2.txt’, 'r') 

for index1, line1 in enumerate(file1): 
    file2.seek(0) # Return to start of file 
    for index2, line2 in enumerate(file2): 
+0

谢谢!最优化的解决方案 –

您需要在每次迭代重新file2。在循环内移动该代码。否则,在第一次外迭代之后,您会到达file2的末尾,并且在外循环的下一轮中您没有剩余部分可以迭代。

+0

我应该在事后注意,我的解决方案我受竞争条件的限制。改用Prune的答案。 –

我会保持每个文件的每一行中单独列出

with open(file1) as f: 
    content_1 = f.readlines() 

with open(file2) as f: 
    content_2 = f.readline() 

,然后进行比较列表

for index1, line1 in enumerate(content_1): 
    for index2, line2 in enumerate(content_2): 
     # do your stuff here 
+0

由此,您必须将每个文件的全部内容存储在内存中,这对于非常大的输入文件可能会有风险(或失败)。 –

+0

一致认为,这对于非常大的文件来说不是一个理想的解决方案,但对于几千行文件应该没问题......在处理非常大的文件时,更好(但较慢)的想法是每次重新打开第二个文件时间 – torresmateo