我有一个字典列表
teachers = [
{
"id": 0,
"goals": ["travel", "relocate", "study"],
},
{
"id": 1,
"goals": ["travel","study"],
},
{
"id": 2,
"goals": ["travel", "work", "study"],
},
{
"id": 3,
"goals": ["work", "relocate", "study"],
}
]
我需要得到字典的一部分,在"工作";在"目标"列表中;:
teachers = [
{
"id": 2,
"goals": ["travel", "work", "study"],
},
{
"id": 3,
"goals": ["work", "relocate", "study"],
}
]
我该如何解决我的问题?
最简洁的解决方案是使用列表推导式
teachers = [t for t in teachers if "work" in t["goals"]]
python中的列表推导,如何?
使用内置函数filter
返回一个迭代器,这将最小化列表推导的开销。如果您只需要一个普通列表作为结果,只需用list()
>>> list(filter(lambda o:"work" in o["goals"], teachers))
[{'id': 2, 'goals': ['travel', 'work', 'study']}, {'id': 3, 'goals': ['work', 'relocate', 'study']}]
裁判:https://docs.python.org/3/library/functions.html过滤器
通过在列表中指向字典的索引来获取字典。
print(teachers[3])
>>>{'id': 3, 'goals': ['work', 'relocate', 'study']}