繁体   English   中英

带有字典索引的值列表

[英]value list with index to dictionary

我想编写一个将索引和列表的值转换为字典的函数,例如:(下面的代码在python中)。

(a, b, c, d) = range(4)
l = [5, 6, 7, 8]
dic = {}
def fun(index_list, l):
    # do something
dic = fun ([a, b, d], l)

>>> print dic
>>> {'0':5, '1':6, '3':8}

要么

`>>> {'a':5, 'b':6, 'c':8}`

任何想法?

第二个结果可能吗?

您不能执行{'a':5, 'b':6, 'c':8} ,因为您不应该以代码逻辑所必需的任何方式将变量名与其值绑定。 有一些令人难以置信的丑陋和脆弱的骇客,可能会让您到达那里,但让我们将这些工具留在棚子里。

要获取值到值,可以轻松zipdict

a, b, c, d = range(4)
lst = [5, 6, 7, 8]
dic = dict(zip((a, b, d), lst))
# dic == {0: 5, 1: 6, 3: 7}

虽然现在我看到您期望3映射到8 您可以这样做,但这是一个额外的步骤。

master_dic = dict(zip((a, b, c, d), lst))
dic = {k:master_dic[k] for k in ('a', 'b', 'd')}

这很简单,但是只需使用dict理解即可:

dic = {str(v): l[v] for v in (a, b, d)}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM