避免列表理解中的冗余

时间:2017-08-06 14:29:40

标签: 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)
)

1 个答案:

答案 0 :(得分: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)
)

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

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)
)

但你考虑过一个功能吗?

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))