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

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)

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


当前回答

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

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]

其他回答

例如,我们想要从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版本中编写的,所以您可能需要针对旧版本进行调整。

你可以这样做

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

但以上需要在list a中搜索2次6,所以尝试except会更快

try:
    a.remove(6)
except:
    pass

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

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

if c in nums:
    nums.remove(c)

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

while c in nums:
    nums.remove(c)

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

这是一个效率较低的解决方案,但它仍然有效:

A =[] //这是你的列表

B //需要删除的元素

counter = a.count(b)

while counter > 0:
    if b in a:
       a.remove(b)
       counter -= 1

print(a)
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]