All, I want to delete specific array elements of one array from the other. Here is an example. The arrays are a long list of words though.
A = ['at','in','the']
B = ['verification','at','done','on','theresa']
I would like to delete words that appear in A from B.
B = ['verification','done','theresa']
Here is what I tried so far
for word in A:
for word in B:
B = B.replace(word,"")
I am getting an error:
AttributeError: 'list' object has no attribute 'replace'
What should I use to get it?
解决方案
Using a list comprehension to get the full answer:
[x for x in B if x not in A]
However, you may want to know more about replace, so ...
python list has no replace method. If you just want to remove an element from a list, set the relevant slice to be an empty list. For example:
>>> print B
['verification', 'at', 'done', 'on', 'theresa']
>>> x=B.index('at')
>>> B[x:x+1] = []
>>> print B
['verification', 'done', 'on', 'theresa']
Note that trying to do the same thing with the value B[x] will not delete the element from the list.