【问题标题】:Most efficient way to search in list of dicts在字典列表中搜索的最有效方法
【发布时间】:2016-08-10 05:50:07
【问题描述】:

我有以下字典列表。

people = [
{'name': "Tom", 'age': 10},
{'name': "Mark", 'age': 5},
{'name': "Pam", 'age': 7}
]

就性能而言,这将是在 dicts 列表中搜索的最优化方式。以下是一些不同的方法:

next((item for item in dicts if item["name"] == "Pam"), None)

filter(lambda person: person['name'] == 'Pam', people)

def search(name):
    for p in people:
        if p['name'] == name:
            return p

def search_dictionaries(key, value, list_of_dictionaries):
    return [element for element in list_of_dictionaries if element[key] == value]

也欢迎任何其他方法。谢谢。

【问题讨论】:

  • 你这样做一次就完事了吗?如果是这样,那么一旦找到该物品就返回是最有意义的。如果不是,请使用可重复用于后续搜索的映射。

标签: python list dictionary


【解决方案1】:

对函数进行快速计时表明使用过滤器似乎是所有方法中最快的

%timeit filter(lambda person: person['name'] == 'Pam', people)

1000000 次循环,3 次中的最佳:每个循环 263 ns

  • 使用 next 会产生 731ns 的时间
  • 使用搜索方法产生的时间为 361ns
  • 最后,seach_dictionaries 使用 811ns

【讨论】:

    【解决方案2】:

    如果您正在搜索单个项目,那么这是“最佳”方法

    def search(name):
        for p in people:
            if p['name'] == name:
                return p
    

    所有其他实现将遍历列表中的所有项目,而一旦找到该项目,这个实现将停止

    【讨论】:

      猜你喜欢
      • 2015-04-02
      • 1970-01-01
      • 2018-10-13
      • 2015-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-25
      • 2021-10-13
      相关资源
      最近更新 更多