我想从列表中删除一个值,如果它存在于列表中(它可能不存在)。
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)
难道没有更简单的方法吗?
我想从列表中删除一个值,如果它存在于列表中(它可能不存在)。
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
其他回答
如果你的元素是不同的,那么一个简单的集合差异就可以了。
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]
你可以这样做
a=[1,2,3,4]
if 6 in a:
a.remove(6)
但以上需要在list a中搜索2次6,所以尝试except会更快
try:
a.remove(6)
except:
pass
正如许多其他答案所述,list.remove()将工作,但如果项不在列表中则抛出ValueError。在python 3.4+中,有一个有趣的方法来处理这个问题,使用suppress contextmanager:
from contextlib import suppress
with suppress(ValueError):
a.remove('b')
这就是我的答案,用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()
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]