在for循环中使用Return [英] Using Return in a for loop

查看:82
本文介绍了在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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆