全部,我想从另一个数组中删除一个数组的特定数组元素。这是一个例子。数组是一长串单词。
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'
我应该用什么来买?
使用列表理解获得完整答案:
但是,您可能想了解更多有关替换的信息,因此。。。
python list没有replace方法。如果只想从列表中删除元素,请将相关切片设置为空列表。例如:
请注意,尝试对值
B[x]
执行相同的操作不会从列表中删除元素。您也可以尝试从B中删除元素,例如:
如果您可以删除B中的重复项,而不关心顺序,则可以坚持设置:
在这种情况下,由于set中的查找比list中的快得多,因此您将获得显著的加速。实际上,在这种情况下,A和B最好是固定的
相关问题 更多 >
编程相关推荐