在python中删除数组元素

编程入门 行业动态 更新时间:2024-10-27 16:35:23
本文介绍了在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中删除数组元素

本文发布于:2023-10-18 02:14:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1502784.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   元素   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!