You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用map lambda从员工字典列表中提取称谓、名和姓?

解决方法:用map+lambda正确拼接员工称谓与姓名

嘿,我看到你想通过map和lambda从员工字典列表里提取并拼接出称谓 名 姓的格式,思路没问题,但之前的写法存在键取值的错误,我来帮你修正~

先说说你之前写法的问题

  • 第一种写法 x["title", "firstname", "lastname"]:你把一个元组当作字典的键来取值,但你的员工字典里根本没有这个元组类型的键,运行会直接抛出KeyError。
  • 第二种写法 x["title"+"firstname"+"lastname"]:这是把三个字符串拼接成了"titlefirstnamelastname",同样你的字典里不存在这个键,自然也取不到对应的值。

正确的实现方式

我们需要分别取出每个员工字典里的title、firstname、lastname三个字段值,再用空格拼接成目标格式,这里有两种常用写法:

写法1:使用f-string(简洁直观)

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"}
]

fullnames_employees = list(map(lambda x: f"{x['title']} {x['firstname']} {x['lastname']}", employees))
print(fullnames_employees)

写法2:使用str.join()(适合字段较多的场景)

fullnames_employees = list(map(lambda x: " ".join([x['title'], x['firstname'], x['lastname']]), employees))

运行结果

两种写法都会得到你期望的输出:

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

内容的提问来源于stack exchange,提问作者Julie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:48:16