Easy way to change generator into list comprehensi

2019-07-20 12:17发布

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?

2条回答
相关推荐>>
2楼-- · 2019-07-20 12:49

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

gen = TransMach(mfile, sfile)
lines = list(gen)
查看更多
SAY GOODBYE
3楼-- · 2019-07-20 12:56

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

查看更多
登录 后发表回答