Python, delete all occurrences of a string in a list

Let's 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 the elements that are in the second list from the main list?

Thank you in advance

Adam

+6
source share
4 answers

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 & . If you need only items that are not found in the second list, we can use the difference, - :

 >>> set(main_array) - set(second_array) set(['cake', 'bacon', 'milk']) 
+7
source
 new_array = [x for x in main_array if x not in second_array] 

However, for large lists this is not very good. You can optimize using the set for 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 elements doesn't matter, you can use a set for both arrays:

 new_array = list(set(main_array) - set(second_array)) 
+11
source
 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']) 
+2
source
 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'] 
0
source

Source: https://habr.com/ru/post/915558/


All Articles