在python中删除数组元素 [英] Deleting array elements in python
问题描述
所有,我想从另一个数组中删除一个数组的特定数组元素.这是一个例子.数组虽然是一长串单词.
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']
我想从B中删除出现在A中的单词.
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,"")
我遇到错误:
AttributeError:列表"对象没有属性替换"
AttributeError: 'list' object has no attribute 'replace'
我应该用什么来获得它?
What should I use to get it?
推荐答案
使用列表推导获得完整答案:
Using a list comprehension to get the full answer:
[x for x in B if x not in A]
但是,您可能想了解有关替换的更多信息,所以...
However, you may want to know more about replace, so ...
python列表没有替换方法.如果只想从列表中删除元素,请将相关的切片设置为空列表.例如:
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:
>>> print B
['verification', 'at', 'done', 'on', 'theresa']
>>> x=B.index('at')
>>> B[x:x+1] = []
>>> print B
['verification', 'done', 'on', 'theresa']
请注意,尝试使用值B[x]
做同样的事情不会从列表中删除该元素.
Note that trying to do the same thing with the value B[x]
will not delete the element from the list.
这篇关于在python中删除数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!