在Python中删除数组元素
大家好,我想从一个数组中删除另一个数组里的特定元素。这里有个例子。这些数组其实是很长的单词列表。
A = ['at','in','the']
B = ['verification','at','done','on','theresa']
我想从B中删除出现在A里的单词。
B = ['verification','done','theresa']
这是我到目前为止尝试的内容:
for word in A:
for word in B:
B = B.replace(word,"")
我遇到了一个错误:
AttributeError: 'list'对象没有'replace'这个属性
我应该用什么来解决这个问题呢?
3 个回答
1
你也可以试着从B中移除一些元素,比如:
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
3
如果你可以接受在B中删除重复的内容,并且不在乎顺序的话,你可以使用集合(sets):
>>> A = ['at','in','the']
>>> B = ['verification','at','done','on','theresa']
>>> list(set(B).difference(A))
['on', 'done', 'theresa', 'verification']
这样做的话,你会发现速度会快很多,因为在集合中查找东西比在列表中快得多。实际上,在这种情况下,把A和B都用集合会更好。
3
使用列表推导式来得到完整的答案:
[x for x in B if x not in A]
不过,你可能想更了解一下replace这个方法,所以……
在Python中,列表是没有replace这个方法的。如果你只是想从列表中删除一个元素,可以把对应的切片设置为空列表。比如:
>>> print B
['verification', 'at', 'done', 'on', 'theresa']
>>> x=B.index('at')
>>> B[x:x+1] = []
>>> print B
['verification', 'done', 'on', 'theresa']
需要注意的是,尝试用值B[x]
来做同样的事情是不会从列表中删除这个元素的。