在Python中最好使用yield的地方? [英] Where to use yield in Python best?

查看:94
本文介绍了在Python中最好使用yield的地方?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道yield的工作方式.我知道排列,就算是数学上的简单.

但是yield的真正力量是什么?我什么时候应该使用它?一个简单而好的例子就更好了.

解决方案

yield当您有一个返回序列的函数并且要遍历该序列,但不需要每个值时,最好使用

yield立刻在内存中.

例如,我有一个python脚本,可解析大量CSV文件,并且我想返回每一行以在另一个函数中进行处理.我不想一次将所有兆字节的数据存储在内存中,所以我yield python数据结构中的每一行.因此,从文件中获取行的功能可能类似于:

def get_lines(files):
    for f in files:
        for line in f:
            #preprocess line
            yield line

然后我可以使用与列表相同的语法来访问此函数的输出:

for line in get_lines(files):
    #process line

但是我节省了大量的内存使用量.

I know how yield works. I know permutation, think it just as a math simplicity.

But what's yield's true force? When should I use it? A simple and good example is better.

解决方案

yield is best used when you have a function that returns a sequence and you want to iterate over that sequence, but you do not need to have every value in memory at once.

For example, I have a python script that parses a large list of CSV files, and I want to return each line to be processed in another function. I don't want to store the megabytes of data in memory all at once, so I yield each line in a python data structure. So the function to get lines from the file might look something like:

def get_lines(files):
    for f in files:
        for line in f:
            #preprocess line
            yield line

I can then use the same syntax as with lists to access the output of this function:

for line in get_lines(files):
    #process line

but I save a lot of memory usage.

这篇关于在Python中最好使用yield的地方?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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