如何在if语句中使用两个条件

时间:2013-07-04 14:06:12

标签: python if-statement

我有以下等式:

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)]但我收到指向&&的语法错误。我测试了我的表达式第一个条件并且它是正确的。

3 个答案:

答案 0 :(得分:8)

您正在寻找and boolean operator

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 ++布尔语法。

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

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