避免列表理解中的冗余

Ell*_*sky 2 python list-comprehension

如何避免sol在此列表理解中不必要地查询设置对象?目前,我为每个对象查询两次,一次在三元组中,一次在谓词中.但是,我想不出更优雅的解决方案.有吗?

dnf = (
    (
        (
            d if p[i,d,True] in sol
            else
            -d if p[i,d,False] in sol
        )
        for d in range(N)
        if p[i,d,True] in sol or p[i,d,False] in sol
    )
    for i in range(M)
)
Run Code Online (Sandbox Code Playgroud)

Ry-*_*Ry- 7

您可以识别该情况None并将其过滤掉:

dnf = (
    (
        x for x in (
            d if p[i,d,True] in sol else
            -d if p[i,d,False] in sol else None
            for d in range(N)
        )
        if x is not None
    )
    for i in range(M)
)
Run Code Online (Sandbox Code Playgroud)

或者以各种方式之一链迭代:

dnf = (
    (
        x
        for d in range(N)
        for x in (
            (d,) if p[i,d,True] in sol else
            (-d,) if p[i,d,False] in sol else ()
        )
    )
    for i in range(M)
)
Run Code Online (Sandbox Code Playgroud)

但你有没有考虑过功能呢?

def get_dnf(N, p, sol, i):
    for d in range(N):
        if p[i,d,True] in sol:
            yield d
        elif p[i,d,False] in sol:
            yield -d


dnf = (get_dnf(N, p, sol, i) for i in range(M))
Run Code Online (Sandbox Code Playgroud)

  • 我投票支持发电机功能:为什么要试图折磨自己弄清楚如何使发电机表达/理解? (2认同)