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
解决方案
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'])