简体   繁体   English

Python:如何对循环进行嵌套枚举?

[英]Python: How to do nested enumerate for loop?

I have two files, file1 and file2 , and for every file1 line, I'm trying to check against all the lines of file2 . 我有两个文件, file1file2 ,对于每个file1行,我试图检查file2所有行。

So I did a nested enumerate for loop, but checking the first line of file1 against all the lines of file2 , the program just completes, rather than moving onto the next file1 line to check against all the lines of file2 . 所以我做了一个嵌套的枚举for循环,但是对照file2所有行检查file1的第一行,程序刚刚完成,而不是移动到下一个file1行来检查file2所有行。

Here is what I have: 这是我有的:

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

How can I check every line of file1 against all the lines of file2 ? 如何针对file2所有行检查file1每一行? What could I be doing wrong here? 我在这里做错了什么?

Thank you in advance and will be sure to upvote/accept answer 提前谢谢你,一定会upvote /接受答复

Push the position of file2 back to the start at the top of each loop. file2的位置推回到每个循环顶部的开头。 Either close and reopen it as aryamccarthy suggested, or do it the cleaner way by simply moving the pointer: 关闭并重新打开它作为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):

You need to reopen file2 on every iteration. 您需要在每次迭代时重新打开file2 Move that code inside the loop. 将该代码移到循环中。 Otherwise, you reach the end of file2 after the first outer iteration, and you have nothing left to iterate over in the next round of the outer loop. 否则,在第一次外部迭代之后到达file2的末尾,并且在下一轮外循环中没有任何东西可以迭代。

I would keep every line of each file in separate lists 我会将每个文件的每一行保存在单独的列表中

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

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

and then proceed to compare the lists 然后继续比较列表

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM