删除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’ object has no attribute ‘replace’

我该怎么用来得到它?

最佳答案 使用列表理解来获得完整的答案:

[x for x in B if x not in A]

但是,您可能想了解更多关于替换的信息,所以……

python列表没有替换方法.如果您只想从列表中删除元素,请将相关切片设置为空列表.例如:

>>> print B
['verification', 'at', 'done', 'on', 'theresa']
>>> x=B.index('at')
>>> B[x:x+1] = []
>>> print B
['verification', 'done', 'on', 'theresa']

请注意,尝试使用值B [x]执行相同操作不会从列表中删除该元素.

点赞