python数组中删除一个元素_删除python中的数组元素

论坛 期权论坛 编程之家     
选择匿名的用户   2021-5-29 21:35   11   0

全部,我想从另一个数组中删除一个数组的特定数组元素.这是一个例子.虽然数组是一长串的单词.

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]执行相同操作不会从列表中删除该元素.

标签:elements,python,arrays

来源: https://codeday.me/bug/20190729/1576737.html

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP