在字典列表中搜索的最有效方法 [英] Most efficient way to search in list of dicts
本文介绍了在字典列表中搜索的最有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下字典列表.
people = [
{'name': "Tom", 'age': 10},
{'name': "Mark", 'age': 5},
{'name': "Pam", 'age': 7}
]
就性能而言,这是在字典列表中进行搜索的最优化方法.以下是一些不同的方法:
Which would be the most optimized way in terms of performance to search in list of dicts. Following are different some methods:
next((item for item in dicts if item["name"] == "Pam"), None)
OR
filter(lambda person: person['name'] == 'Pam', people)
OR
def search(name):
for p in people:
if p['name'] == name:
return p
OR
def search_dictionaries(key, value, list_of_dictionaries):
return [element for element in list_of_dictionaries if element[key] == value]
也欢迎使用任何其他方法.谢谢.
Any other method is also welcome. Thanks.
推荐答案
对函数进行快速计时表明,使用过滤器似乎是所有方法中最快的方法
Doing a quick timeit on the functions show that using filter seems to be the fastest of all the methods
%timeit filter(lambda person: person['name'] == 'Pam', people)
1000000次循环,每个循环最好3:263 ns
1000000 loops, best of 3: 263 ns per loop
- 使用next产生的时间为731ns
- 使用搜索方法会产生361ns的时间
- 最后,seach_dictionaries使用811ns
这篇关于在字典列表中搜索的最有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文