0

I can not figure out why my code does not filter out lists from a predefined list. I am trying to remove specific list using the following code.

data = [[1,1,1],[1,1,2],[1,2,1],[1,2,2],[2,1,1],[2,1,2],[2,2,1],[2,2,2]]
data = [x for x in data if x[0] != 1 and x[1] != 1]

print data

My result:

data = [[2, 2, 1], [2, 2, 2]]

Expected result:

data = [[1,2,1],[1,2,2],[2,1,1],[2,1,2],[2,2,1],[2,2,2]]
4

5 回答 5

3

and is wrong, use or

data = [x for x in data if x[0] != 1 or x[1] != 1]
于 2012-10-26T22:35:27.283 回答
2

and仅当双方都是真值时才为真。也许你想要...

data = [x for x in data if x[0] != 1 or x[1] != 1]
于 2012-10-26T22:35:43.237 回答
0

我认为这就是OP想要的。

data = [[1,1,1],[1,1,2],[1,2,1],[1,2,2],[2,1,1],[2,1,2],[2,2,1],[2,2,2]]

data = [x for x in data if x[:2] != [1,1]]
print data

data = [x for x in data if ((x[0],x[1]) != (1,1))]   
print data
于 2012-10-26T22:45:30.250 回答
0

你有一个小的逻辑错误。要匹配您对问题的思考方式,请使用:

if not (x[0] == 1 and x[1] == 1)

请注意,这在逻辑上等同于 using or,正如其他人所建议的那样:

not (A and B) == (not A) or (not B) 
于 2012-10-26T22:57:47.793 回答
0

在您的代码中,应使用“或”代替“和”。如果您想执行这两个值,则使用“and”。例子:

data = [x for x in data if x[0] != 1 or x[1] != 1]
于 2021-10-22T16:44:02.100 回答