简体   繁体   English

Python,删除列表中出现的所有字符串

[英]Python, remove all occurrences of string in list

Say i have a list: 说我有一个清单:

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

and another list: 和另一个清单:

second_list = ['cheese', 'tomato']

and I want to remove all elements that are found in the second list, from the main list? 我想从主列表中删除第二个列表中找到的所有元素?

Thank you in advance 先感谢您

Adam 亚当

new_array = [x for x in main_array if x not in second_array]

However, this is not very performant for large lists. 但是,对于大型列表而言,这不是很有效。 You can optimize by using a set for second_array : 您可以使用second_array的集合进行second_array

second_array = set(second_array)
new_array = [x for x in main_array if x not in second_array]

If the order of the items does not matter, you can use a set for both arrays: 如果项目的顺序无关紧要,您可以为两个数组使用一个集合:

new_array = list(set(main_array) - set(second_array))

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'])
main_array = set(['bacon', 'cheese', 'milk', 'cake', 'tomato'])
second_array = (['cheese', 'tomato'])

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

main_array.intersection(second_array)
>>> set(['cheese', 'tomato'])
l = [u'SQOOP', u'SOLR', u'SLIDER', u'SFTP', u'PIG', u'NODEMANAGER', u'JSQSH', u'HCAT', u'HBASE_REGIONSERVER', u'GANGLIA_MONITOR', u'FLUME_HANDLER', u'DATANODE', u'BIGSQL_WORKER']

p = [u'SQOOP', u'SOLR', u'SLIDER', u'SFTP']

l = [i for i in l if i not in [j for j in p]]

print l
[u'PIG', u'NODEMANAGER', u'JSQSH', u'HCAT', u'HBASE_REGIONSERVER', u'GANGLIA_MONITOR', u'FLUME_HANDLER', u'DATANODE', u'BIGSQL_WORKER']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM