簡體   English   中英

Python:如何對循環進行嵌套枚舉?

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

我有兩個文件, file1file2 ,對於每個file1行,我試圖檢查file2所有行。

所以我做了一個嵌套的枚舉for循環,但是對照file2所有行檢查file1的第一行,程序剛剛完成,而不是移動到下一個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()

如何針對file2所有行檢查file1每一行? 我在這里做錯了什么?

提前謝謝你,一定會upvote /接受答復

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

您需要在每次迭代時重新打開file2 將該代碼移到循環中。 否則,在第一次外部迭代之后到達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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM