Python 使用列表值将列表与字典匹配
我试图通过比较一个列表和一个以列表为其值的字典来获取关键字。科目是我的清单,学校是我的字典Python 使用列表值将列表与字典匹配,python,python-2.7,Python,Python 2.7,我试图通过比较一个列表和一个以列表为其值的字典来获取关键字。科目是我的清单,学校是我的字典 subjects = ['English','Mathematics'] Schools = {'School1': ['English','Mathematics','Humanities'], 'School2': ['English','Science','Programming'], 'School3': ['English','Art','Mathematics']} 在这种情况下,我找不到钥
subjects = ['English','Mathematics']
Schools = {'School1': ['English','Mathematics','Humanities'],
'School2': ['English','Science','Programming'],
'School3': ['English','Art','Mathematics']}
在这种情况下,我找不到钥匙。我的预期输出是返回School1和School3,这是一行代码
x = [school_name
for school_name, school_content in Schools.items()
if all(
subject in school_content
for subject in subjects
)
]
# ['School1', 'School3']
据我所知,您希望返回包含
subject
list项的列表。如果是这样,您可以这样实现它:
result=[]
for item in Schools:
contains_all = all(elem in Schools[item] for elem in subjects)
if contains_all:
result.append(Schools[item])
我所做的是,若学校
列表中的项目包含主题,则将其附加到结果
列表中