我想从列表中删除一个值,如果它存在于列表中(它可能不存在)。
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)
难道没有更简单的方法吗?
当前回答
也许你的解决方案适用于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来实现更多python化:
for i, element in enumerate(reversed(list)):
if condition(element):
del list[(i+1)*-1]
print(list)
其他回答
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]
以下是如何做到这一点(不需要理解列表):
def remove_all(seq, value):
pos = 0
for item in seq:
if item != value:
seq[pos] = item
pos += 1
del seq[pos:]
如果你的元素是不同的,那么一个简单的集合差异就可以了。
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]
我们也可以使用.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]
>>>
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)