将列表映射到字典 [英] Map list onto dictionary

查看:175
本文介绍了将列表映射到字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以将列表映射到字典上?我想要做的是给它提供一个函数,该函数将返回键的名称,并且该值将是原始值.例如;

Is there a way to map a list onto a dictionary? What I want to do is give it a function that will return the name of a key, and the value will be the original value. For example;

somefunction(lambda a: a[0], ["hello", "world"])
=> {"h":"hello", "w":"world"}

(这不是我要执行的特定示例,我希望像map()这样的通用函数可以执行此操作)

(This isn't a specific example that I want to do, I want a generic function like map() that can do this)

推荐答案

我认为不存在能够完全做到这一点的标准函数,但是使用内置的dict和理解函数构造一个简单的函数很容易:

I don't think a standard function exists that does exactly that, but it's very easy to construct one using the dict builtin and a comprehension:

def somefunction(keyFunction, values):
    return dict((keyFunction(v), v) for v in values)

print somefunction(lambda a: a[0], ["hello", "world"])

输出:

{'h': 'hello', 'w': 'world'}

但是为此功能想出一个好名字比实现它更困难.我将其留给读者练习.

But coming up with a good name for this function is more difficult than implementing it. I'll leave that as an exercise for the reader.

这篇关于将列表映射到字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆