【问题标题】:How to prevent reading next line when next() is used in an if statement [duplicate]在 if 语句中使用 next() 时如何防止读取下一行[重复]
【发布时间】:2018-04-22 21:23:30
【问题描述】:

我有台词:

for line in f:
    if 'ipsum' in next(f):    #just want to check
        print("Hello")

我想要的是只检查下一行的内容,而不是整体跳转到下一行。我想要的是这样的:

for line in f:
    if 'ipsum' in next(f):    #just checking
        print("Hello")
        next(f) #then actually jump to the next line

还有其他方法可以做到这一点吗?

【问题讨论】:

  • ''' junk.txt 是:一二三...十''' import sys filehandle = open("junk.txt", "r") lines = filehandle.readlines() currentline = 0 for line in lines: if currentline == len(lines) - 1: continue nextline = currentline + 1 if "three" in lines[nextline]: print (line) currentline += 1 #试着回答这个,写了起来,现在无法提交答案:(这行得通。

标签: python python-3.x


【解决方案1】:

恐怕你不能这样做。我认为您将不得不使用列表来存储文件的行。您正在使用迭代器,如果不实际调用 next(),您将看不到下一步是什么

【讨论】:

    猜你喜欢
    • 2016-07-15
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 2017-09-27
    • 2020-03-16
    • 2014-01-23
    相关资源
    最近更新 更多