我想从列表中删除一个值,如果它存在于列表中(它可能不存在)。
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)
难道没有更简单的方法吗?
当前回答
例如,我们想要从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版本中编写的,所以您可能需要针对旧版本进行调整。
其他回答
通过索引除希望删除的元素之外的所有内容来覆盖列表
>>> s = [5,4,3,2,1]
>>> s[0:2] + s[3:]
[5, 4, 2, 1]
更普遍的是,
>>> s = [5,4,3,2,1]
>>> i = s.index(3)
>>> s[:i] + s[i+1:]
[5, 4, 2, 1]
这是一个效率较低的解决方案,但它仍然有效:
A =[] //这是你的列表
B //需要删除的元素
counter = a.count(b)
while counter > 0:
if b in a:
a.remove(b)
counter -= 1
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)
一些最简单的基准测试方法:
import random
from copy import copy
sample = random.sample(range(100000), 10000)
remove = random.sample(range(100000), 1000)
%%timeit
sample1 = copy(sample)
remove1 = copy(remove)
for i in reversed(sample1):
if i in remove1:
sample1.remove(i)
# 271 ms ± 16 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
# remove all instances
%%timeit
sample1 = copy(sample)
remove1 = copy(remove)
filtered = list(filter(lambda x: x not in remove1, sample1))
# 280 ms ± 18.9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
# remove all instances
%%timeit
sample1 = copy(sample)
remove1 = copy(remove)
filtered = [ele for ele in sample1 if ele not in remove1]
# 293 ms ± 72.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
# remove all instances
%%timeit
sample1 = copy(sample)
remove1 = copy(remove)
for val in remove1:
if val in sample1:
sample1.remove(val)
# 558 ms ± 40.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
# only remove first occurrence
%%timeit
sample1 = copy(sample)
remove1 = copy(remove)
for val in remove1:
try:
sample1.remove(val)
except:
pass
# 609 ms ± 11.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
# only remove first occurrence
考虑:
a = [1,2,2,3,4,5]
要去除所有的事件,可以使用python中的filter函数。 例如,它看起来是这样的:
a = list(filter(lambda x: x!= 2, a))
因此,它将保留a != 2的所有元素。
只要拿出其中一项使用
a.remove(2)