使用map()和lambda函数格式化键值

2024-06-17 15:05:31 发布

您现在位置:Python中文网/ 问答频道 /正文

给定下面单元格中定义的员工列表,处理字典列表以创建一个员工姓名列表,其格式为title firstname lastname,例如Jonathan Calderon先生等

到目前为止,我可以打印出标题,但仅此而已。。。你知道吗

我的工作:

new_list2 = list(map(lambda x: x["title"], employees)) 
print(new_list2)

输出:

['Mr', 'Mr', 'Mrs', 'Ms']

词典列表:

employees = [
    {
        "email": "jonathan2532.calderon@gmail.com",
        "employee_id": 101,
        "firstname": "Jonathan",
        "lastname": "Calderon",
        "title": "Mr",
        "work_phone": "(02) 3691 5845"
    },
    {
        "email": "christopher8710.hansen@gmail.com",
        "employee_id": 102,
        "firstname": "Christopher",
        "lastname": "Hansen",
        "title": "Mr",
        "work_phone": "(02) 5807 8580"
    },
    {
        "email": "isabella4643.dorsey@gmail.com",
        "employee_id": 103,
        "firstname": "Isabella",
        "lastname": "Dorsey",
        "title": "Mrs",
        "work_phone": "(02) 6375 1060"
    },
    {
        "email": "barbara1937.baker@gmail.com",
        "employee_id": 104,
        "firstname": "Barbara",
        "lastname": "Baker",
        "title": "Ms",
        "work_phone": "(03) 5729 4873"
    }
]

预期产量:

Mr Jonathan Calderon
Mr Christopher Hansen
Mrs Isabella Dorsey
Ms Barbara Baker

Tags: comid列表titleemailemployeephonefirstname
2条回答

因为OP要求map(),这里先生,是使用它的解决方案,并且只使用它(不需要导入额外的库):

result = map(lambda x: [x['title'],x["firstname"],x["lastname"]],employees)
print(*["{} {} {}\n".format(a,b,c) for a,b,c in result], sep="")

Output:
Mr Jonathan Calderon
Mr Christopher Hansen
Mrs Isabella Dorsey
Ms Barbara Baker

您可以使用列表理解并使用^{}从每个字典中获取感兴趣的值:

from operator import itemgetter
l = ['title', 'firstname', 'lastname']

[' '.join(itemgetter(*l)(i)) for i in employees]

输出

['Mr Jonathan Calderon', 'Mr Christopher Hansen', 'Mrs Isabella Dorsey', 'Ms Barbara Baker']

或者如果您喜欢使用map

[' '.join(map(lambda x: i.get(x), l)) for i in employees]
# ['Mr Jonathan Calderon', 'Mr Christopher Hansen', 'Mrs Isabella Dorsey', 'Ms Barbara Baker']

相关问题 更多 >