基于python字典列表的多个条件的子集

use*_*827 1 python dictionary

基于这种在字典列表中搜索的最有效方法

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

在上面的字典列表中,如何获取带有name == Tom和的字典的年龄列表att == 12?仅针对一种条件执行此操作:

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

我还希望解决方案适用于 python 2.7 和 3.6

Joh*_*ooy 5

filter在 Python3.x 中不返回列表。你应该使用列表理解

[x['age'] for x in people if x['name'] == "Tom" and x['att'] == 12]
Run Code Online (Sandbox Code Playgroud)

旁白:搜索并不是特别有效,但这取决于您选择的数据结构。如果您要进行多次查找,这很重要,因为 dict 的大小也越来越大。您应该使用不同的数据结构或维护辅助数据结构。这与如何在数据库中使用索引类似。