簡體   English   中英

如何有效地從 python 中的二維列表中刪除值列表?

[英]How to remove a list of values from a 2D list in python efficiently?

假設我們有這個數組:

people = [[Amy, 25], [Bella, 30], [Charlie, 29], [Dean, 21], [Elliot, 19]]

我有一個要從中刪除的名稱列表:

people_rem = [Amy, Charlie, Dean]

這樣我們的最終數組將如下所示:

final_people = [[Bella, 30], [Elliot, 19]]

我曾嘗試使用列表理解來執行此操作,它有效,但速度非常慢(不是在這種特定情況下,但在我的實際使用中,我有很多列表,其中包含更多項目):

final_people = [person for person in people if people[0] not in people_rem]

我將如何以高效和快速的方式做到這一點?

您正在使用僅支持線性查找的數據結構。 您可以使用bisect模塊進行對數時間查找(刪除仍然是線性時間),但是當有一個結構可以讓您進行恆定時間查找和刪除時,為什么還要麻煩呢?

使用字典:

people = dict(people)

現在刪除是微不足道的:

for name in people_rem:
    del people[name]

請注意,這在O(len(people_rem))時間內運行,而不是O(len(people)) 由於大概len(people_rem) < len(people_rem) ,這是一件好事(TM)。 我沒有計算O(len(people))到字典的轉換,因為你很可能在首先創建people時直接執行此操作,這不會比構建初始列表更昂貴。

您是否嘗試過通過 pandas 進行操作? 檢查這是否更快。

import pandas as pd

people = [['Amy', 25], ['Bella', 30], ['Charlie', 29], ['Dean', 21], ['Elliot', 19]]

people_rem = ['Amy', 'Charlie', 'Dean']

def remove(people, people_rem):
    df = pd.DataFrame(people, columns = ['Name', 'Age'])
    for person in people_rem:
        df.drop(df[df.Name == person].index, inplace=True)
    return df.values.tolist()

final_people = remove(people, people_rem)
print(final_people)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM