【问题标题】:Formatting key values using map() with a lambda function使用带有 lambda 函数的 map() 格式化键值
【发布时间】:2019-03-29 16:11:05
【问题描述】:

给定在下面单元格中定义的员工列表,处理字典列表以创建格式化为标题 firstname lastname 的员工姓名列表,例如乔纳森·卡尔德隆先生等

到目前为止,我可以打印出标题,但仅此而已......

我的工作:

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

【问题讨论】:

  • 我正在考虑做 new_list2 = list(map(lambda x,y,z: x["title"]y["firstname"]z["lastname"], employees)) 但那不工作..
  • 你定义的函数需要三个参数,但 map 只会传递一个参数。只需在 lambda 中使用一个参数并完全按照您正在做的事情(显然,替换另外两个)

标签: python list dictionary lambda


【解决方案1】:

您可以使用列表推导式并使用 operator.itemgetter 从每个字典中获取感兴趣的值:

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']

【讨论】:

  • 我正在尝试使用 map() lambda 函数来获取它,但无论如何感谢 :)
  • 也可以使用map@KevinW,查看更新答案
  • 这对@KevinW 有帮助吗?如果是,请不要忘记接受,请参阅What should I do when someone answers my question?
  • 这太好了,我只是想了解员工中 i.get(x) 和 for i 的部分
  • 查看 doncs List Comprehensions 了解更多信息。 dict.get(i) 只是字典的一种方法,通过指定键来获取值。
【解决方案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

【讨论】:

  • 这太好了,我想了解打印行中的星号(*) 和 sep="" 是做什么的?
  • 当然。星号展开列表的内容,因此 print 语句可以打印出由空格分隔的每个元素。 sep="",告诉 print 语句打印“”(什么都不是)而不是空格,从而消除元素之间的空格。如果没有 sep="",则在第一个条目之后会有一个空格,使后面的名称缩进 1。
猜你喜欢
  • 2015-07-26
  • 2012-11-10
  • 2022-07-07
  • 1970-01-01
  • 1970-01-01
  • 2018-03-22
  • 1970-01-01
  • 2021-05-28
  • 1970-01-01
相关资源
最近更新 更多