给定:
a = [[1,2],[3,4],[5,6],[7,8]]
b = 3
我想要删除一个以b
为第一项的a
项目。所以在这个例子中,我们将删除[3,4]
,结果如下:
a = [[1,2],[5,6],[7,8]]
我的现有代码是:
if b in [i[0] for i in a]:
pos = [i[0] for i in a].index(b)
del a[pos]
这个方法可以实现,但速度较慢。有没有更好的方法?
编辑: 我之前没有测试过性能,所以可能做错了,但我得到了这个结果:
def fun1():
lst = [[x, 2*x] for x in range(1000000)]
lst = [x for x in lst if x[0] != 500]
return lst
def fun2():
lst = [[x, 2*x] for x in range(1000000)]
for i in reversed(range(len(lst))):
if lst[i][0] == 500:
del lst[i]
return lst
cProfile.runctx('fun1()', None, locals())
6 function calls in 0.460 seconds
cProfile.runctx('fun2()', None, locals())
6 function calls in 0.502 seconds