问题
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?
回答1:
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.
回答2:
If you are ok to delete duplicates in B and don't care about order, you can stick up with sets:
>>> A = ['at','in','the']
>>> B = ['verification','at','done','on','theresa']
>>> list(set(B).difference(A))
['on', 'done', 'theresa', 'verification']
In this case you'll get a significant speedup as lookup in set is much faster than in list. Actually, in this case it's better A and B to be sets
回答3:
You could also try removing the elements from B, ex :
A = ['at','in','the']
B = ['verification','at','done','on','theresa']
print B
for w in A:
#since it can throw an exception if the word isn't in B
try: B.remove(w)
except: pass
print B
来源:https://stackoverflow.com/questions/7459246/deleting-array-elements-in-python