python删除数组元素_在python中删除数组元素

这篇博客讨论了如何从一个列表(B)中删除出现在另一个列表(A)中的元素。作者尝试使用`replace`方法,但遇到了错误。解决方案是使用列表推导式,通过条件过滤出不在A列表中的元素。另外,也提到了如果要删除指定索引的元素,可以使用切片操作来实现。博客还介绍了Python列表没有`replace`方法的事实,并提供了相关的代码示例。
摘要由CSDN通过智能技术生成

1586010002-jmsa.png

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?

解决方案

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 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']

Note that trying to do the same thing with the value B[x] will not delete the element from the list.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值