在 for 循环中使用 Return

编程入门 行业动态 更新时间:2024-10-28 00:16:40
本文介绍了在 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

本文发布于:2023-10-26 01:25:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1528675.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Return

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!