在for循环中使用Return

编程入门 行业动态 更新时间:2024-10-27 14:19:52
本文介绍了在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.1上Python 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.

因此,您将像这样使用它:

So you'd use it like this:

for new_line in read_log_lines(filename): # new_line was produced by the generator function

更多推荐

在for循环中使用Return

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

发布评论

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

>www.elefans.com

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