Easy way to change generator into list comprehension without duplicating code in python?

一世执手 提交于 2019-12-12 18:02:25

问题


I have something like this:

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

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?


回答1:


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

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



回答2:


Calling list() on the generator transforms it into a normal list.



来源:https://stackoverflow.com/questions/18078511/easy-way-to-change-generator-into-list-comprehension-without-duplicating-code-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!