您使用了错误的运算符。你想要布尔值and
;&
是位运算符:
[(i,j,k) for (i,j,k) in [(i,j,k) for i in {-4,-2,1,2,5,0} for j in {-4,-2,1,2,5,0} for k in {-4,-2,1,2,5,0} if (i+j+k > 0 and (i!=0 and j!=0 and k!=0)) ] ]
您可以消除嵌套列表理解,它是多余的:
[(i,j,k) for i in {-4,-2,1,2,5,0} for j in {-4,-2,1,2,5,0} for k in {-4,-2,1,2,5,0} if (i+j+k > 0 and (i!=0 and j!=0 and k!=0))]
接下来,使用该itertools.product()
函数生成所有组合而不是嵌套循环,并all()
测试所有值是否非零:
from itertools import product
[t for t in product({-4,-2,1,2,5,0}, repeat=3) if sum(t) > 0 and all(t)]
0
但你也可以从集合中省略并为自己保存all()
测试:
from itertools import product
[t for t in product({-4,-2,1,2,5}, repeat=3) if sum(t) > 0]
也许您想将该测试更正为等于0:
from itertools import product
[t for t in product({-4,-2,1,2,5}, repeat=3) if sum(t) == 0]
结果:
>>> [t for t in product({-4,-2,1,2,5}, repeat=3) if sum(t) == 0]
[(1, 1, -2), (1, -2, 1), (2, 2, -4), (2, -4, 2), (-4, 2, 2), (-2, 1, 1)]