小编And*_* M.的帖子

搜索词典列表的最有效方法

我有以下的dicts列表.

people = [
{'name': "Tom", 'age': 10},
{'name': "Mark", 'age': 5},
{'name': "Pam", 'age': 7}
]
Run Code Online (Sandbox Code Playgroud)

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

next((item for item in dicts if item["name"] == "Pam"), None)
Run Code Online (Sandbox Code Playgroud)

要么

filter(lambda person: person['name'] == 'Pam', people)
Run Code Online (Sandbox Code Playgroud)

要么

def search(name):
    for p in people:
        if p['name'] == name:
            return p
Run Code Online (Sandbox Code Playgroud)

要么

def search_dictionaries(key, value, list_of_dictionaries):
    return [element for element in list_of_dictionaries if element[key] == value]
Run Code Online (Sandbox Code Playgroud)

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

python dictionary list

13
推荐指数
2
解决办法
2万
查看次数

标签 统计

dictionary ×1

list ×1

python ×1