【问题标题】:How to simplify a list comprehension of distributions in python如何简化python中分布的列表理解
【发布时间】:2018-05-23 21:57:08
【问题描述】:

在 scipy.stats 中获取连续分布的对象 这是示例代码: getditributions.py

import scipy.stats as st


CONTINUOUS_DISTRIBUTIONS = [getattr(st,d) for d in dir(st) if isinstance(getattr(st,d), st.rv_continuous)]

print ('number of distributions = ', len(CONTINUOUS_DISTRIBUTIONS))

print ('CONTINUOUS_DISTRIBUTIONS = ')
print(CONTINUOUS_ DISTRIBUTIONS)

Obs:此代码有效,但我在列表理解中调用了两次 getattr。 如何简化此代码以只调用一次 getattr?还是替代解决方案?

【问题讨论】:

    标签: python scipy statistics distribution


    【解决方案1】:

    您可以使用普通的for-loop

    例如:

    CONTINUOUS_DISTRIBUTIONS = []
    for d in dir(st):
        val = getattr(st,d)     #Store in variable for re-use.
        if isinstance(val, st.rv_continuous):
            CONTINUOUS_DISTRIBUTIONS.append(val)
    

    【讨论】:

    • 谢谢!这很好用!列表推导式由包含表达式的括号组成,后跟一个 for 子句,然后是零个或多个 for 或 if 子句。无法在列表理解中使用 val。来自stackoverflow.com/questions/29820026/…
    • 是的,你是对的。列表推导式中不能有变量。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-26
    • 2017-02-13
    • 2014-10-29
    • 1970-01-01
    相关资源
    最近更新 更多