![](/img/trans.png)
[英]Removing duplicates from a list of lists based on a comparison of an element of the inner lists
[英]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
我想刪除的項目a
有b
,因為它是第一項。 因此,在這種情況下,我們將[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
反向刪除a
,就地修改它:
for i in reversed(range(len(a))):
if a[i][0] == 3:
del a[i]
就地修改意味着這樣做效率更高,因為它不會創建新列表(如列表理解那樣)。
由於OP要求提供timeit
解決方案,因此這里是兩個最受歡迎的答案之間的時間比較。
設定 -
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,因為它不必像列表理解那樣在內存中生成新列表。
您可以使用列表理解:
>>> a = [[1,2],[3,4],[5,6],[7,8]]
>>> b = 3
>>> a = [x for x in a if x[0] != b]
>>> a
[[1, 2], [5, 6], [7, 8]]
for i in a[:-1]:
if i[0]==b:
a.remove(i)
那這個呢?
輸出是
[[1、2],[5、6],[7、8]
如果您的列表很小,那么您也可以嘗試filter,
a = [[1,2],[3,4],[5,6],[7,8]]
b = 3
print(list(filter(lambda x:x[0]!=b,a)))
輸出:
[[1, 2], [5, 6], [7, 8]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.