删除python中的阵列元素
所有,我想从另一个数组中删除一个特定的数组元素。这是一个例子。阵列是一长串单词。
A = ['at','in','the']
B = ['verification','at','done','on','theresa']
我想删除出现在B中的单词。
B = ['verification','done','theresa']
这是我到目前为止尝试的错误
for word in A:
for word in B:
B = B.replace(word,"")
:我遇到了一个错误:
attributeError:'list'对象没有属性'替换'
我应该用什么来获得它?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用列表理解来获得完整的答案:
但是,您可能想进一步了解替换,因此...
Python列表没有替换方法。如果您只想从列表中删除元素,请将相关切片设置为空列表。例如:
请注意,尝试使用值
b [x]
进行相同的操作不会从列表中删除元素。Using a list comprehension to get the full answer:
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:
Note that trying to do the same thing with the value
B[x]
will not delete the element from the list.如果您可以删除 B 中的重复项并且不关心顺序,则可以坚持使用集合:
在这种情况下,您将获得显着的加速,因为集合中的查找比集合中的查找快得多。列表。实际上,在这种情况下最好设置 A 和 B
If you are ok to delete duplicates in B and don't care about order, you can stick up with sets:
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
您还可以尝试从 B 中删除元素,例如:
You could also try removing the elements from B, ex :