根据每个列表的第一个元素从列表中删除项目 [英] Removing an item from a list of lists based on each of the lists first element
问题描述
给出:
a = [[1,2],[3,4],[5,6],[7,8]]
b = 3
我要删除以b
作为第一项的a
项.因此,在这种情况下,我们将删除[3,4]
给予:
I would like to remove an item of a
that has b
as it's first item. So in this case we would remove [3,4]
to give:
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]
这有效,但是速度很慢.更好的方法是什么?
This works but it is slow. What would a better way to do this be?
我之前没有测试过性能,所以我可能做错了,但是我得到了:
I've not tested performance before so I may be doing this wrong but I get this:
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
推荐答案
反向删除a
,对其进行就地修改:
Reverse delete a
, modifying it in-place:
for i in reversed(range(len(a))):
if a[i][0] == 3:
del a[i]
就地修改意味着它效率更高,因为它不会创建新列表(如列表理解那样).
An in-place modification means that this is more efficient, since it does not create a new list (as a list comprehension would).
由于OP请求一种高效的解决方案,因此下面是两个投票最高的答案之间的timeit
比较.
Since OP requests a performant solution, here's a timeit
comparison between the two top voted answers here.
设置-
a = np.random.choice(4, (100000, 2)).tolist()
print(a[:5])
[[2, 1], [2, 2], [3, 2], [3, 3], [3, 1]]
列表理解-
%timeit [x for x in a if x[0] != b]
11.1 ms ± 685 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
反向删除-
%%timeit
for i in reversed(range(len(a))):
if a[i][0] == 3:
del a[i]
10.1 ms ± 146 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)
它们确实很接近,但是反向删除的性能提高了1UP,因为它不必像列表理解那样在内存中生成新列表.
They're really close, but reverse delete has a 1UP on performance because it doesn't have to generate a new list in memory, as the list comprehension would.
这篇关于根据每个列表的第一个元素从列表中删除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!