-3

我在列表理解中有这个 if 表达式:

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

但它似乎不是在我的条件之间进行评估,而是在或之间进行评估。为什么会这样?

问题是当 i,j 和 k 之一为 0 时,不添加元组,这不是我想要的。我只想在它们都为 0 时发出。即:我希望结果中包含 0,3,-3。

4

3 回答 3

4

If you still want a one-liner, then the following is actually readable:

[i for i in itertools.product(range(-3, 3), repeat=3) 
 if any(i) and sum(i) == 0]
于 2013-07-13T13:26:13.283 回答
3

(i,j,k)要仅在它们为零时省略,请使用条件(i,j,k) != (0,0,0)

S = range(-3,3)
x = [(i,j,k)
     for i in S
     for j in S
     for k in S
     if ((i+j+k==0)
         and (i,j,k) != (0,0,0))]
print(x)

印刷

[(-3, 1, 2), (-3, 2, 1), (-2, 0, 2), (-2, 1, 1), (-2, 2, 0), (-1, -1, 2), (-1, 0, 1), (-1, 1, 0), (-1, 2, -1), (0, -2, 2), (0, -1, 1), (0, 1, -1), (0, 2, -2), (1, -3, 2), (1, -2, 1), (1, -1, 0), (1, 0, -1), (1, 1, -2), (1, 2, -3), (2, -3, 1), (2, -2, 0), (2, -1, -1), (2, 0,
-2), (2, 1, -3)]

要了解原始条件出了什么问题,请(i!=0) and (j!=0) and (k!=0)

考虑当i=0和时会发生什么j=1

| i != 0 | j != 0 | (i!=0) and (j!=0) | (i,j) != (0,0) |
| False  | True   | False             | True           |

(i!=0) and (j!=0)False因为False and TrueFalse。相反,(i,j) != (0,0)总是True,除非两者ij为零。

添加(k!=0)使示例更复杂,但想法是相同的。

于 2013-07-13T13:18:10.300 回答
1

You could simplify this greatly using itertools...

from itertools import combinations_with_replacement as icwr

S = [t for t in icwr(range(-3,3),3) if t != (0,0,0)]

print S

This is much simpler... (if it is what you want to do!)

于 2013-07-13T13:25:21.403 回答