如何删除列表中两个值的所有出现?

时间:2017-03-06 09:39:30

标签: python list

我想使用一行删除列表中两个值的所有出现。我尝试了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有问题,但我无法弄清楚我应该怎么写这个。

你能帮忙吗?

1 个答案:

答案 0 :(得分:0)

如果i不在非理想列表中,您可以过滤掉:

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]