3

我一直在寻找,但无法弄清楚这件事。

我来自 Java 背景,如果有帮助,我会尝试学习 python。

a = [
    (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 & (i!=0 & j!=0 & k!=0))
        ]
]

语句是:获取总和为零的所有元组,但其中不应该有 0。

始终,此结果由所有元组组成。:(

4

5 回答 5

9

在python中,&是一个位运算符。根据您的需要,您应该使用and.

于 2013-07-10T07:31:01.947 回答
9

您使用了错误的运算符。你想要布尔值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)]
于 2013-07-10T07:31:31.880 回答
3

正如其他人已经说过的那样,您使用了错误的运算符。

这本身不是问题,因为您只组合(或者更确切地说,尝试组合)布尔值。

But the & and the and operator have different precedence.

(i+j+k > 0 and (i!=0 and j!=0 and k!=0))

would be right, as and has a higher precedence than > and !=.

However,

(i+j+k > 0 & (i!=0 & j!=0 & k!=0))

turns out to be

(i+j+k > (0 & (i != (0 & j) != (0 & k) !=0)))

which makes the right hand evaluate to 0, and the expression i + j + k > 0 seems to be true for nearly all your data.

于 2013-07-10T07:48:51.843 回答
1

其他人正在解决错误的问题。是的,and是逻辑的,并且&是按位的,但由于操作数是布尔值,它碰巧实际上不会影响您的代码。哎呀;这实际上确实会影响您的代码,因为优先级不同。但是,除此之外,您还有一个错字:

i+j+k > 0

应该

i + j + k == 0

如果你想要总和为 0 的元组。

于 2013-07-10T07:42:39.590 回答
1

使用 itertools.product 和 sum():

from itertools import product

list1 = (-4,-2,1,2,5,0)
list2 = (-4,-2,1,2,5,0)

print [ couple for couple in product(list1, list2) if not sum(couple) ]
于 2013-07-10T07:45:01.763 回答