【问题标题】:Easy way to change generator into list comprehension without duplicating code in python?无需在 python 中复制代码即可将生成器更改为列表理解的简单方法?
【发布时间】:2013-08-07 08:40:14
【问题描述】:

我有这样的事情:

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有一些叫做descriptor的特性,可以用来修改函数而不接触函数的主体,在这种情况下是否合适?如果是,这里应该如何使用?

【问题讨论】:

    标签: python generator list-comprehension generator-expression


    【解决方案1】:

    只需在生成器上调用list(),在您需要具体化结果的情况下:

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2013-08-27
        • 2021-08-23
        • 2015-12-02
        • 1970-01-01
        • 2017-10-15
        • 1970-01-01
        • 1970-01-01
        • 2021-11-28
        • 2015-06-08
        相关资源
        最近更新 更多