简体   繁体   English

试图弄清楚如何使用 python 中的循环获取下一个值

[英]trying to figure out how to get the next values using a loop in python

I am looking for some resource, my code print the first unequal value between two txt files.我正在寻找一些资源,我的代码打印了两个 txt 文件之间的第一个不相等的值。 what I am trying to do is how to get to the next unequal values if I press a key.我想要做的是如果我按下一个键,如何获得下一个不相等的值。 I think the while loop would help, but I fail in every logic.我认为 while 循环会有所帮助,但我在每个逻辑上都失败了。 any resource where I could find some answers?任何我可以找到答案的资源?

def textdiff():
    text1 = open("text1.txt", "r")
    text2 = open("text2.txt", "r")
    for orgtext1 in text2:
        for oldtext2 in text1:
            if oldtext2 != orgtext1:
                return oldtext2
        text1.close()
        text2.close()


print(textdiff())

thanks a lot多谢

If you want to compare the nth character of file 1 with the nth character of file 2, I would useyield to jump out of the function after each found inequality and the with statement to make sure that the files are properly closed if an error is raised:如果要将文件 1 的第 n 个字符与文件 2 的第 n 个字符进行比较,我将使用yield在每个发现不等式和with语句后跳出函数,以确保在出现错误时正确关闭文件提高:

def textdiff():
    with open("text1.txt", "r") as file1:
        with open("text2.txt", "r") as file2:
            text1 = file1.read()
            text2 = file2.read()
            shared_length = min(len(text1), len(text2))
            for pos in range(shared_length):
                if text1[pos] != text2[pos]:
                    yield text1[pos] + " != " + text2[pos]

for diff in textdiff():
    print(diff)
    input('Press <Return> to continue')

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

相关问题 试图弄清楚如何在Python 3.3.0中正确使用while循环 - Trying to Figure out how to properly use a while loop in Python 3.3.0 试图找出如何根据另一列的行值转换特定列中的某些值 - Trying to figure out how to transform certain values in a specific column based on row values from another column 带有下一行值的Python循环 - Python loop with next row values 试图找出将多行处理成字典的正确循环 - Trying to figure out the correct loop for processing multiple lines into a dictionary 试图弄清楚如何在从字典调用 class 时将变量从一个 class 传递到另一个 python - Trying to figure out how to pass variables from one class to another in python while calling a class from a dictionary 尝试在Python 3中使用Selenium获取文本 - Trying to get Get text out using selenium in Python 3 找出试图在一个模块python中使用导入的模块名称 - Figure out the module name trying to use imports in one module python 使用 Python 3.7 和 Selenium,我不知道如何解决我的代码中的视口元素问题 - Using Python 3.7 and Selenium, I can't figure out how to troubleshoot my code for out of Viewport elements 陷入无限循环,不知道为什么 - python - Stuck in infinite loop, cant figure out why - python 我试图从网页中使用正则表达式python获取代理 - im trying to get proxies using regex python out of a web page
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM