问题
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