Python:从列表中删除项目并保持原始列表顺序

时间:2018-07-24 21:32:23

标签: python python-3.x list set

我有动物清单:

list_animals = ['dog', 'cat', 'cow', 'tiger', 'lion', 'snake', 'lion']

和一组宠物:

set_pets = set(['dog', 'cat'])

我想从set_pets中删除list_animals中的宠物,但仍然保留list_animals的原始顺序。这可能吗?

我试图做: set(list_animals) - set_pets,但不保留原始动物订单...

谢谢!

2 个答案:

答案 0 :(得分:1)

您可以通过列表理解轻松地做到这一点:

result = [a for a in list_animals if a not in set_pets]
['cow', 'tiger', 'lion', 'snake', 'lion']

我这里有第二种使用list.remove()的方法,但是效率低下。 List comp是必经之路。

答案 1 :(得分:0)

input

输出

list_animals = ['dog', 'cat', 'cow', 'tiger', 'lion', 'snake', 'lion']
set_pets = set(['dog', 'cat'])
list_animals = list(filter(lambda x: x not in set_pets, list_animals))
print(list_animals)
相关问题