【问题标题】:Partial Matching a list of values to dictionary keys将值列表部分匹配到字典键
【发布时间】:2021-07-09 15:33:02
【问题描述】:

我正在尝试清理原始联系信息的数据框。原始数据给出了一个人的头衔,我需要根据头衔确定资历。如果标题与字典键部分匹配,我需要将该键的值附加到新列表中。本质上,我需要遍历列表中的每个标题,看看是否存在与任何字典键的部分匹配并获取相应的字典值并将该值附加到新列表中。我尝试了多种格式的 for 循环和列表理解,但没有成功。

这是列表和字典的示例:

title = ['CEO', 'CFO', 'Financial Analyst', 'Associate', 'Tax Manager', 'Audit Manager']
seniority_dict = {'CEO':'Exec', 'CFO':'Exec', 'Manager':'Manager', 'Analyst':'Associate', 'Associate':'Associate'}

这是上面列表中相应值的资历

seniority = ['Exec', 'Exec', 'Associate', 'Associate', 'Manager', 'Manager']

【问题讨论】:

    标签: python list dataframe dictionary mapping


    【解决方案1】:

    如果您没有不在标题中的密钥

    title = ['Software Engineer', 'CEO', 'CFO', 'Financial Analyst', 'QA Engineer', 'Associate', 'Tax Manager', 'Audit Manager']
    seniority_dict = {'CEO': 'Exec', 'CFO': 'Exec', 'Manager': 'Manager', 'Analyst': 'Associate', 'Associate': 'Associate'}
    
    new_list = []
    for t in title:
        found = False
        for key, value in seniority_dict.items():
            if key in t:
                new_list.append(value)
                found = True
                break
        if not found:
            new_list.append('NaN')
    print(new_list)
    

    【讨论】:

    • 这行得通,谢谢!如何解释与键不匹配的标题。我希望那些等于 nan 所以新列表的长度等于标题列表的长度
    • 忘记标记抱歉
    • @ParthPatel 更新了我的答案。你可以根据你的要求追加。
    猜你喜欢
    • 2022-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-24
    • 2021-11-22
    • 2011-09-24
    • 2019-01-23
    相关资源
    最近更新 更多