我想从列表中删除一个值,如果它存在于列表中(它可能不存在)。
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)
难道没有更简单的方法吗?
当前回答
这是一个效率较低的解决方案,但它仍然有效:
A =[] //这是你的列表
B //需要删除的元素
counter = a.count(b)
while counter > 0:
if b in a:
a.remove(b)
counter -= 1
print(a)
其他回答
如果你知道要删除什么值,这里有一个简单的方法(就像我能想到的一样简单):
a = [0, 1, 1, 0, 1, 2, 1, 3, 1, 4]
while a.count(1) > 0:
a.remove(1)
你会得到 [0,0,2,3,4]
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)
这里的许多答案都涉及到创建一个新列表。这涉及到将所有数据从旧列表复制到新列表(删除的项除外)。如果你的清单很长,你可能负担不起(或者你不应该想要)。
在这些情况下,就地更改列表要快得多。如果你必须从列表中删除一个以上的元素,这可能会很棘手。假设您循环遍历列表,并删除了一个项,那么列表将更改,标准for循环将不考虑这一点。循环的结果可能不是您所期望的。
例子:
a = [0, 1, 2, 3, 4, 5]
for i in a:
a.remove(i) # Remove all items
print(a)
Out: [1, 3, 5]
一个简单的解决方案是以相反的顺序遍历列表。在这种情况下,你会得到:
a = [0, 1, 2, 3, 4, 5]
for i in reversed(a):
a.remove(i) # Remove all items
print(a)
Out: []
然后,如果你只需要删除一些特定值的元素,你可以简单地在循环中放入一个if语句,结果是:
a = [0, 1, 2, 3, 4, 5]
for i in reversed(a):
if i == 2 or i == 3: # Remove all items having value 2 or 3.
a.remove(i)
print(a)
Out: [0, 1, 4, 5]
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]
考虑:
a = [1,2,2,3,4,5]
要去除所有的事件,可以使用python中的filter函数。 例如,它看起来是这样的:
a = list(filter(lambda x: x!= 2, a))
因此,它将保留a != 2的所有元素。
只要拿出其中一项使用
a.remove(2)