Using Return in a for loop(在 for 循环中使用 Return)
问题描述
我正在编写一个程序来读取本地存储在 C 驱动器上的日志文件.这个日志文件不断更新,我的程序只打印日志中的新文本行,而不是以前存储的行.我需要在控制台中打印行的相同函数来返回行本身.我能看到的唯一方法是将 return 放在 for 循环中,但这是不可能的,因为它结束了函数.
I am making a program that reads through a log file that is stored locally on the C drive. This log file is constantly being updated and my program only prints the new lines of text in the log, not the previously stored lines. I need the same function that prints lines in the console to return the line itself. The only way I can see of doing that is to put return in the for loop but that is not possible as it ends the function.
我需要这个读取行的函数来返回该行,因为返回的行将被发送到另一个函数,该函数解释该行以识别其中的某些数据.
I need this function that read lines to return the line also because the returned line will be sent to another function that interprets the line to recognize certain data in it.
如何在函数中循环返回或将数据从函数传递到另一个函数?
How would I loop a return in a function or pass data from a function onto another function?
我使用的是 Windows 8.1Python v2.7.9
I am on Windows 8.1 Python v2.7.9
推荐答案
使用 生成器函数 在您迭代时生成数据.生成器可以在您对其进行迭代时无休止地生成数据:
Use a generator function to produce data as you iterate. Generators can produce data endlessly while you iterate over them:
def read_log_lines(filename):
while True:
# code to read lines
if is_new(line):
yield line
该函数在调用时返回一个生成器对象.然后,您可以像遍历列表一样遍历该对象,并且每次迭代生成器函数中的代码都会运行,直到它到达 yield
语句.此时,产生的值将作为迭代的下一个值返回,并且生成器函数将暂停,直到您再次迭代.
This function, when called, returns a generator object. You can then loop over that object like you can over a list, and each time you iterate the code in the generator function will be run until it reaches a yield
statement. At that point the yielded value is returned as the next value for the iteration, and the generator function is paused until you iterate again.
所以你会这样使用它:
for new_line in read_log_lines(filename):
# new_line was produced by the generator function
这篇关于在 for 循环中使用 Return的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 for 循环中使用 Return
基础教程推荐
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 筛选NumPy数组 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01