我想从列表中删除一个值,如果它存在于列表中(它可能不存在)。

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

del a[b]
print(a)

上面给出了错误:

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)

难道没有更简单的方法吗?


当前回答

使用一个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

其他回答

这就是我的答案,用while和for就可以了

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()

另一种可能是使用set而不是list,如果set适用于您的应用程序。

IE中如果你的数据不是有序的,并且没有副本,那么

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

是没有错误的。

通常,列表只是一个方便的容器,用于存放实际上是无序的项目。有些问题询问如何从列表中删除一个元素的所有出现。如果你一开始就不想被骗,一套也很方便。

my_set.add(3)

不改变上面的my_set。

这个例子是快速的,并且会从列表中删除一个值的所有实例:

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

当nums是列表,c是要删除的值时:

要删除列表中第一个出现的c,只需执行以下操作:

if c in nums:
    nums.remove(c)

要从列表中删除所有出现的c,请执行以下操作:

while c in nums:
    nums.remove(c)

添加异常处理将是最佳实践,但我主要想演示如何从列表中删除所有出现的元素。

一句话:

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

有时它很有用。

更简单:

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