gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:55:04 25 4
gpt4 key购买 nike

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

所以我做了一个嵌套的枚举 for 循环,但是检查 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 的所有行?我在这里做错了什么?

预先感谢您,一定会投票/接受答案

最佳答案

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

关于Python:如何做嵌套枚举for循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43262762/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com