繁体   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