使用带有lambda函数的map()格式化键值

时间:2019-03-29 16:11:05

标签: python list dictionary lambda

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

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

我的工作:

htaccess

输出:

htaccess

词典列表:

RewriteCond %{HTTP_HOST} ^(www\.)(.*) [NC]
RewriteRule (.*) https://%2%{REQUEST_URI} [R=301,L]
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

预期输出:

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

2 个答案:

答案 0 :(得分:3)

您可以使用列表推导,并使用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']

答案 1 :(得分:1)

自从OP请求 $dir = $_SERVER['DOCUMENT_ROOT'] . '/images/products/'; $imgData = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $this->input->post('croppedData'))); $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $charactersLength = strlen($characters); $randomString = ''; for ($i = 0; $i < 10; $i++) { $randomString .= $characters[rand(0, $charactersLength - 1)]; } $randomString .= ".jpg"; file_put_contents($dir . $randomString, $imgData); 以来,先生,这里是使用它且仅使用它的解决方案(不需要导入其他库):

map()