1

我有以下等式:

result=[(i,j,k) for i in S for j in S for k in S if sum([i,j,k])==0]

我想在 if 语句中添加另一个条件,使我的结果集不包含 (0,0,0)。我尝试执行以下操作: result=[(i,j,k) for i in S for j in S for k in S if sum([i,j,k])==0 && (i,j,k)!=(0,0,0)]但我收到指向&&. 我测试了第一个条件的表达式,它是正确的。

4

3 回答 3

8

您正在寻找and布尔运算符

result=[(i,j,k) for i in S for j in S for k in S if sum([i,j,k])==0 and (i,j,k)!=(0,0,0)]

&&JavaScriptJavaPerlPHP、Ruby、Go、OCaml、Haskell、MATLAB、R、Lasso、ColdFusion、C、C# 或 C++ 布尔语法。

于 2013-07-04T14:07:06.427 回答
6

除了那个错误而不是三重嵌套for循环之外,您还可以itertools.product在此处使用来获取笛卡尔积S * S * S

from itertools import product
result=[ x for x in product(S, repeat = 3) if sum(x)==0 and x != (0,0,0)]

演示:

>>> S = [1, -1, 0, 0]
>>> [ x for x in product(S, repeat = 3) if sum(x) == 0 and x != (0,0,0)]
[(1, -1, 0), (1, -1, 0), (1, 0, -1), (1, 0, -1), (-1, 1, 0), (-1, 1, 0), (-1, 0, 1), (-1, 0, 1), (0, 1, -1), (0, -1, 1), (0, 1, -1), (0, -1, 1)]
于 2013-07-04T14:11:00.533 回答
5
result = [(i, j, k) for i in S
          for j in S
          for k in S
          if sum([i, j, k]) == 0 and (i, j, k) != (0, 0, 0)]
于 2013-07-04T14:06:55.800 回答