Python: 嵌套枚举for循环怎么做?

Python: How to do nested enumerate for loop?

我有两个文件,file1file2,对于每个 file1 行,我试图检查 file2 的所有行。

所以我做了一个嵌套的枚举 for 循环,但是检查 file1 的第一行与 file2 的所有行,程序就完成了,而不是移动到下一个 [=12] =] 行来检查 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()

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

提前谢谢你,一定会upvote/accept回答

您需要在每次迭代时重新打开 file2。将该代码移动到循环内。否则,在第一次外循环后到达 file2 的末尾,并且在下一轮外循环中没有任何内容可迭代。

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):

我会将每个文件的每一行都放在单独的列表中

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