[英]How to remove certain lists from a list of lists using python?
我不明白為什么我的代碼沒有從預定義的列表中過濾掉列表。 我正在嘗試使用以下代碼刪除特定列表。
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
我的結果:
data = [[2, 2, 1], [2, 2, 2]]
預期結果:
data = [[1,2,1],[1,2,2],[2,1,1],[2,1,2],[2,2,1],[2,2,2]]
and
是錯誤的,請使用or
data = [x for x in data if x[0] != 1 or x[1] != 1]
and
僅在雙方均為真值時才為真。 也許你想要...
data = [x for x in data if x[0] != 1 or x[1] != 1]
我認為這就是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
您有一個小邏輯錯誤。 要匹配您對問題的思考方式,請使用:
if not (x[0] == 1 and x[1] == 1)
請注意,從邏輯上講,這等效於使用or
,就像其他人建議的那樣:
not (A and B) == (not A) or (not B)
在您的代碼中,“或”應該用於代替“和”。 如果你想同時執行這兩個值,就使用“and”。所以代碼應該像 data = [x for x in data if x[0] != 1 or x[1] != 1]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.