yield关键字Question(对不同的文件运行函数)



如果我想实现以下逻辑,我不确定是否需要收益率

def function():
items = ["1", "2", "3"]
for item in items:
print(item)
function()

现在,这将首先在执行时运行第一行,如果运行了特定的if语句,我想再次运行该函数,它将使用第一行。实际应该做的是在每次呼叫中运行下一行:

if ... is None:
function() # choose second item, ifstatement is executed again, choose third item etc...

希望有人能在那里帮助我(我在github copilot中写了以下内容,它建议我遵循pice代码,我不确定这是否是我需要的(:

# for loop, which don't use the first line on every execution and if the function is called a second time, the forloop will start from the second line within a file called lines.txt
def getline():
with open('lines.txt', 'r') as f:
for line in f:
yield line

IIUC,您正在列表上寻找迭代器,获取下一项的方法是使用next函数-

items = [1, 2, 3]
item_iterator = iter(items)
print(next(item_iterator))
# prints 1
print(next(item_iterator))
# prints 2
print(next(item_iterator))
# prints 3
print(next(item_iterator))
# raises StopIteration

最新更新