简体   繁体   中英

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

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 (ie 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?

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

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

在生成器上调用list()会将其转换为普通列表。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM