比较字典列表与列表

时间:2020-06-09 09:33:49

标签: python

我正在尝试比较字典列表和是否存在匹配增量等级。有没有更好的方法(更有效的方法)来做到这一点。我的代码:

requirements = ["JSF","JSP","Spring"]
Employee_records = [{'job_seeker_id': 1, 'skills': ['Spring', 'JSP', 'JSF'], 'experience': '5 years', 'location': 'stockholm', 'rank': 3}, {'job_seeker_id': 2, 'skills': ['Servlets', 'JSP'], 'experience': '2 years', 'location': 'gothenburg', 'rank': 1}, {'job_seeker_id': 3, 'skills': ['JSP'], 'experience': '4 years', 'location': 'lund', 'rank': 1}, {'job_seeker_id': 4, 'skills': ['Servlets'], 'experience': '3 years', 'location': 'malmo', 'rank': 0}, {'job_seeker_id': 5, 'skills': ['Hibernate', 'Servlets'], 'experience': '1 years', 'location': 'stockholm', 'rank': 0}]

for dict_ in Employee_records:
    for elm in dict_["skills"]:
        for skill in requirements:
            if elm == skill:
                dict_["rank"]+=1

3 个答案:

答案 0 :(得分:0)

假设requirements中没有重复项,那么:

for skill in requirements:
    if elm == skill:

实际上等同于:

if elm in requirements:

因此您可以简化为:

for dict_ in Employee_records:
    for skill in dict_["skills"]:
        if skill in requirements:
            dict_["rank"] += 1

但是,您实际上并不需要通过所有skills并检查它们是否在requierments中,只需检查它们之间的交点即可:

req = set(requirements)

for emp in Employee_records:
    emp['rank'] += len(set(emp['skills']) & req)

您应将list转换为set,以进行有效的操作。

答案 1 :(得分:0)

使用set可以使代码更整洁,并且更具Python风格,尽管性能不会有太大变化。

requirements = {"jsp", "jsf", "string"}
for employee in employees:
    employee["rank"] += len(set(employee["skills"]) & requirements)

答案 2 :(得分:0)

for dict_ in Employee_records:
    dict_["rank"] += len(set(dict_["skills"]) & set(requirements)
相关问题