有没有一种简单的方法可以按值删除列表元素?

a = [1, 2, 3, 4]
b = a.index(6)

del a[b]
print a

上面显示了以下错误:

Traceback (most recent call last):
  File "D:\zjm_code\a.py", line 6, in <module>
    b = a.index(6)
ValueError: list.index(x): x not in list

所以我必须这样做:

a = [1, 2, 3, 4]

try:
    b = a.index(6)
    del a[b]
except:
    pass

print a

但是,没有简单的方法可以做到这一点吗?


#1楼

如果您知道要删除的值,这是一种简单的方法(无论如何,我仍然可以想到):

a = [0, 1, 1, 0, 1, 2, 1, 3, 1, 4]
while a.count(1) > 0:
    a.remove(1)

您会得到[0, 0, 2, 3, 4]


#2楼

考虑:

a = [1,2,2,3,4,5]

要排除所有情况,可以在python中使用filter函数。 例如,它看起来像:

a = list(filter(lambda x: x!= 2, a))

因此,它将保留!= 2的所有元素。

仅取出其中一项使用

a.remove(2)

#3楼

要删除列表中元素的首次出现,只需使用list.remove

>>> a = ['a', 'b', 'c', 'd']
>>> a.remove('b')
>>> print a
['a', 'c', 'd']

请注意,它不会删除所有出现的元素。 为此使用列表理解。

>>> a = [10, 20, 30, 40, 20, 30, 40, 20, 70, 20]
>>> a = [x for x in a if x != 20]
>>> print a
[10, 30, 40, 30, 40, 70]

#4楼

你可以做

a=[1,2,3,4]
if 6 in a:
    a.remove(6)

但以上需要在列表中搜索6 2次,因此尝试使用除外会更快

try:
    a.remove(6)
except:
    pass

#5楼

通过使用列表的remove方法,可以更轻松地在列表中查找值,然后删除该索引(如果存在)。

>>> a = [1, 2, 3, 4]
>>> try:
...   a.remove(6)
... except ValueError:
...   pass
... 
>>> print a
[1, 2, 3, 4]
>>> try:
...   a.remove(3)
... except ValueError:
...   pass
... 
>>> print a
[1, 2, 4]

如果您经常这样做,则可以将其包装在一个函数中:

def remove_if_exists(L, value):
  try:
    L.remove(value)
  except ValueError:
    pass

#6楼

通常,如果您告诉Python做一些它无法做的事情,它将抛出一个Exception,因此您必须执行以下任一操作:

if c in a:
    a.remove(c)

要么:

try:
    a.remove(c)
except ValueError:
    pass

只要它是您期望的并且可以正确处理的异常,它就不一定是一件坏事。


#7楼

这是就地执行此操作的方法(无需列表理解):

def remove_all(seq, value):
    pos = 0
    for item in seq:
        if item != value:
           seq[pos] = item
           pos += 1
    del seq[pos:]

#8楼

是。 这是我发现最有用的:

import sys

a = [1, 2, 3, 4]

y = 0

if y < 1:
      a.remove(1)
      print len(a)
else:
    sys.exit()

现在.remove()仅接受一个参数,因此您只能从列表中删除一个整数。


#9楼

这个例子很快,并且将从列表中删除该值的所有实例:

a = [1,2,3,1,2,3,4]
while True:
    try:
        a.remove(3)
    except:
        break
print a
>>> [1, 2, 1, 2, 4]

#10楼

如果集合适用于您的应用程序,则另一种可能性是使用集合而不是列表。

IE,如果您的数据未排序,并且没有重复,则

my_set=set([3,4,2])
my_set.discard(1)

没有错误。

通常,列表只是用于方便实际存放无序物品的容器。 有些问题询问如何从列表中删除所有出现的元素。 如果您不想一开始就喜欢做傻瓜,那么再说一遍就很方便了。

my_set.add(3)

不会从上面改变my_set。


#11楼

如果您的元素是不同的,那么简单的集合差异就可以了。

c = [1,2,3,4,'x',8,6,7,'x',9,'x']
z = list(set(c) - set(['x']))
print z
[1, 2, 3, 4, 6, 7, 8, 9]

#12楼

我们也可以使用.pop:

>>> lst = [23,34,54,45]
>>> remove_element = 23
>>> if remove_element in lst:
...     lst.pop(lst.index(remove_element))
... 
23
>>> lst
[34, 54, 45]
>>> 

#13楼

通过索引除您要删除的元素以外的所有内容来覆盖列表

>>> s = [5,4,3,2,1]
>>> s[0:2] + s[3:]
[5, 4, 2, 1]

#14楼

有一个for循环和一个条件:

def cleaner(seq, value):    
    temp = []                      
    for number in seq:
        if number != value:
            temp.append(number)
    return temp

如果要删除一些但不是全部:

def cleaner(seq, value, occ):
    temp = []
    for number in seq:
        if number == value and occ:
            occ -= 1
            continue
        else:
            temp.append(number)
    return temp

#15楼

 list1=[1,2,3,3,4,5,6,1,3,4,5]
 n=int(input('enter  number'))
 while n in list1:
    list1.remove(n)
 print(list1)

#16楼

举例来说,我们要从x中删除所有1。 这就是我要做的:

x = [1, 2, 3, 1, 2, 3]

现在,这是我的方法的实际用法:

def Function(List, Unwanted):
    [List.remove(Unwanted) for Item in range(List.count(Unwanted))]
    return List
x = Function(x, 1)
print(x)

这是我的方法,只需一行:

[x.remove(1) for Item in range(x.count(1))]
print(x)

两者都将其作为输出:

[2, 3, 2, 3, 2, 3]

希望这可以帮助。 PS,请注意,这是在3.6.2版中编写的,因此您可能需要针对旧版本进行调整。


#17楼

如许多其他答案所述, list.remove()可以工作,但是如果该项目不在列表中,则抛出ValueError 。 在python 3.4及更高版本中,有一种有趣的方法可以使用抑制上下文管理器来处理此问题:

from contextlib import suppress
with suppress(ValueError):
    a.remove('b')

#18楼

arr = [1, 1, 3, 4, 5, 2, 4, 3]

# to remove first occurence of that element, suppose 3 in this example
arr.remove(3)

# to remove all occurences of that element, again suppose 3
# use something called list comprehension
new_arr = [element for element in arr if element!=3]

# if you want to delete a position use "pop" function, suppose 
# position 4 
# the pop function also returns a value
removed_element = arr.pop(4)

# u can also use "del" to delete a position
del arr[4]

#19楼

这将从数组sys.argv删除所有"-v"实例,并且如果没有找到实例,也不会抱怨:

while "-v" in sys.argv:
    sys.argv.remove('-v')

您可以在名为speechToText.py的文件中查看运行中的代码:

$ python speechToText.py -v
['speechToText.py']

$ python speechToText.py -x
['speechToText.py', '-x']

$ python speechToText.py -v -v
['speechToText.py']

$ python speechToText.py -v -v -x
['speechToText.py', '-x']

#20楼

也许您的解决方案适用于int,但不适用于字典。

一方面,remove()对我不起作用。 但也许它适用于基本类型。 我猜下面的代码也是从对象列表中删除项目的方法。

另一方面,“ del”也无法正常工作。 就我而言,使用python 3.6:当我尝试使用'del'命令从'for'bucle中的列表中删除元素时,python会更改进程中的索引,并且bucle会在时间之前过早停止。 仅当您以相反的顺序删除一个元素时,它才有效。 这样,您无需更改待处理元素数组索引

然后,我用了:

c = len(list)-1
for element in (reversed(list)):
    if condition(element):
        del list[c]
    c -= 1
print(list)

其中“列表”类似于[{'key1':value1'},{'key2':value2},{'key3':value3},...]

另外,您可以使用enumerate做更多的pythonic操作:

for i, element in enumerate(reversed(list)):
    if condition(element):
        del list[(i+1)*-1]
print(list)

#21楼

一行:

a.remove('b') if 'b' in a else None

有时很有用。

更简单:

if 'b' in a: a.remove('b')

#22楼

语法:lst.remove(x)

lst = ['one', 'two', 'three', 'four', 'two']

lst.remove('two') #it will remove first occurence of 'two' in a given list

del lst[2] #delete item by index value

print(lst)

#23楼

这就是我的回答,只是用whilefor

def remove_all(data, value):
    i = j = 0
    while j < len(data):
        if data[j] == value:
            j += 1
            continue
        data[i] = data[j]
        i += 1
        j += 1
    for x in range(j - i):
        data.pop()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值