使用Python删除数组元素

2024-10-01 22:33:56 发布

您现在位置: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'

我应该用什么来买?


Tags: thein元素foron数组单词replace
3条回答

使用列表理解获得完整答案:

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

但是,您可能想了解更多有关替换的信息,因此。。。

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

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

请注意,尝试对值B[x]执行相同的操作不会从列表中删除元素。

您也可以尝试从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

如果您可以删除B中的重复项,而不关心顺序,则可以坚持设置:

>>> A = ['at','in','the']
>>> B = ['verification','at','done','on','theresa']
>>> list(set(B).difference(A))
['on', 'done', 'theresa', 'verification']

在这种情况下,由于set中的查找比list中的快得多,因此您将获得显著的加速。实际上,在这种情况下,A和B最好是固定的

相关问题 更多 >

    热门问题