我可以在字典上使用map lambda来打印3个或更多项目吗?
答案 0 :(得分:0)
您无法访问dictionaries
之类的x["title", "firstname", "lastname"]
的多个元素;您需要为每个元素执行一次。
提取所需的元素后,可以将它们与' '.join
结合起来:
def extract(person):
return ' '.join(person[key] for key in ['title', 'firstname', 'lastname'])
fullnames_employees = [extract(person) for person in employees]
print(fullnames_employees)
输出:
['Mr Jonathan Calderon', 'Mr Christopher Hansen', 'Mrs Isabella Dorsey', 'Ms Barbara Baker']
答案 1 :(得分:0)
除了lambda,我使用了简单的for循环:
for i in employees:
print(i["title"]+ " " + i["firstname"] + " " + i["lastname"] )
结果:
Mr Jonathan Calderon
Mr Christopher Hansen
Mrs Isabella Dorsey
Ms Barbara Baker
或简单列表理解:
print([i["title"]+ " " + i["firstname"] + " " + i["lastname"] for i in employees])
礼物:
['Mr Jonathan Calderon', 'Mr Christopher Hansen', 'Mrs Isabella Dorsey', 'Ms Barbara Baker']
答案 2 :(得分:0)
您的lambda函数是正确的,但是从迭代元素获取数据的方式是错误的,无法访问,只能将每个元素数据加1并将其添加到字符串中并返回。 / p>
输入数据
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: '{} {} {}'.format(x["title"],x["firstname"],x["lastname"]), employees))
输出
['Mr Jonathan Calderon',
'Mr Christopher Hansen',
'Mrs Isabella Dorsey',
'Ms Barbara Baker']