2017-03-06 77 views
0

我想使用一行刪除列表中兩個值的所有出現。我嘗試了filter + lambda方法和列表理解,但它不按我期望的方式工作。如何刪除列表中兩個值的所有出現?

喜歡的東西:

s2 = [0, 0, 3, 11, 14, 17, 18, 18] 
# I want to remove all 0 and 18 from s2 list 
# i.e. I want output: s2_filter = [3, 11, 14, 17] 

s2_filter = filter (lambda a: a != 0 or 18, s2) 
>>> s2 = [0, 0, 3, 11, 14, 17, 18, 18] # not what I'm expecting 

s2_filter = [i for i in s2 if i != 0 or 18] 
>>> s2 = [0, 0, 3, 11, 14, 17, 18, 18] # not what I'm expecting 

我想有一些錯誤的or,但我想不出我應該怎麼正確地寫這個。

你能幫忙嗎?

+0

不好的例子,我將修改它。有時它們只發生一次,有時不止一次。 – francoiskroll

+1

不,我!= 0,我!= 18'與'和... –

+0

或'我不在(0,18)' –

回答

0

你可以只篩選了,如果我在非理想的名單是不是:

s2 = [0, 0, 3, 11, 14, 17, 18, 18] 
s2_filter = [i for i in s2 if i not in [0, 18]] 
s2_filter 
[3, 11, 14, 17] 
相關問題