您使用了錯誤的操作你想boolean and
; &
is a bitwise operator:
[(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()
function至g enerate所有的組合,而不是嵌套循環,並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)]
外部理解的原因是什麼?它實際上並沒有做任何有用的事情,但你必須有寫作的理由。 – user2357112
真的,我第一次嘗試沒有它..但它仍然沒有工作..因此,我看到它是否適用於它.. – abhididdigi