Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在目录列表中搜索的最有效方法_Python_List_Dictionary - Fatal编程技术网

Python 在目录列表中搜索的最有效方法

Python 在目录列表中搜索的最有效方法,python,list,dictionary,Python,List,Dictionary,我有下面的目录 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) 或 或 或 任何其他方法也是受欢迎的。谢谢。如果您正在搜索单个项目,那么这是“最

我有下面的目录

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)


任何其他方法也是受欢迎的。谢谢。

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


所有其他实现将迭代列表中的所有项,而此实现将在找到项后停止

执行快速计时。在函数中,使用筛选器似乎是所有方法中最快的

%timeit过滤器(lambda person:person['name']='Pam',people)

1000000个循环,最好3个:每个循环263纳秒

  • 使用next产生731ns的时间
  • 使用搜索方法产生361ns的时间
  • 最后,seach_字典使用811ns

您只做过一次吗?如果是这样的话,那么在找到物品后立即返回最有意义。如果不是,则使用可重复使用的映射进行后续搜索。
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]
def search(name):
    for p in people:
        if p['name'] == name:
            return p