将生成器更改为列表推导的简单方法,而无需在python中复制代码? [英] Easy way to change generator into list comprehension without duplicating code in python?

查看:68
本文介绍了将生成器更改为列表推导的简单方法,而无需在python中复制代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的东西:

class TransMach:
    def __init__(self, machfile, snpfile):
        self.machfile = machfile
        self.snpfile = snpfile

    def __translines(self):
        fobj = open(self.machfile)
        lines = (l.strip().split()[2] for l in fobj)
        tlines = zip(*lines)
        return tlines

使用生成器是为了避免将整个文件读取到内存中,但是有时读取整个文件正是所需要的(即列表理解).我如何在没有太多额外代码的情况下更改这种行为?目标是能够在这两种模式之间进行选择.我听说python有一个称为描述符的功能,可以在不触及功能主体的情况下用于修改功能,在这种情况下是否合适?如果是,在这里应该如何使用?

Generator is used in order to avoid reading the whole file into memory, but sometimes reading the whole file is exactly what is desirable (i.e. list comprehension). How can I change this kind of behavior without too much extra code? The goal is to be able to choose between these two modes. I heard python has some feature called descriptor which can be used to modified functions without touching the body of the function, is it suitable in this case? If yes, how should it be used here?

推荐答案

仅在生成器上调用list(),这些情况下您需要实现结果:

Just call list() on the generator for those occasions you need the result to be materialized:

gen = TransMach(mfile, sfile)
lines = list(gen)

这篇关于将生成器更改为列表推导的简单方法,而无需在python中复制代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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