Python,删除列表中所有出现的字符串 [英] Python, remove all occurrences of string in list

查看:1841
本文介绍了Python,删除列表中所有出现的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个清单:

main_list = ['bacon', 'cheese', 'milk', 'cake', 'tomato']

和另一个列表:

second_list = ['cheese', 'tomato']

我想从主列表中删除第二个列表中找到的所有元素吗?

and I want to remove all elements that are found in the second list, from the main list?

提前谢谢

亚当

推荐答案

如果顺序不重要,则可以使用集合:

If the order is not important you can use sets:

>>> main_array = ['bacon', 'cheese', 'milk', 'cake', 'tomato']
>>> second_array = ['cheese', 'tomato']
>>> set(main_array) & set(second_array)
set(['tomato', 'cheese'])

在这里,我们使用交集运算符&.如果您只希望在第二个列表中找不到物品,我们可以使用差异-:

Here we use the intersection operator, &. Should you only want items not found in your second list, we can use difference, -:

>>> set(main_array) - set(second_array)
set(['cake', 'bacon', 'milk'])

这篇关于Python,删除列表中所有出现的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆