定义Python字典时,如何使用给定字段的值来计算其他字段?

时间:2018-01-25 16:13:35

标签: python dictionary definition

考虑代码

a = 2
b = 3
mylist = {'a' : a, 'b' : b, 'product' : a * b}

这将生成三个字段的字典,其中第三个字段使用第一个和第二个的值计算。我正在寻找mylist的更紧凑的定义。我试过(1)

mylist = {'a' : 2, 'b' : 3, 'product' : a * b}

给出错误

  

NameError:name' a'未定义

和(2)

mylist = {'a' : 2, 'b' : 3, 'product' : mylist['a'] * mylist['b']}

给出错误

  

NameError:name' mylist'未定义

我想找一个更短的命令形式(1),因为你不需要提及字典的名称。也许存在类似currentdictionary['a']的东西?

3 个答案:

答案 0 :(得分:4)

在这种情况下,我会使用类似计算属性的东西。它会在您需要时懒惰地评估该物业;在通话时间。比主动管理产品作为键值对更加强大。

class Pair(object):
    def __init__(self, a, b):
        self.a = a
        self.b = b

    @property
    def product(self):
        return self.a * self.b

示例输出:

>>> Pair(2, 3).product
6

在这里使用字典是可能的,但是作为一个强化解决方案让我感到震惊,(1)你需要与查询是否存在查找上的密钥以及(2)进行竞争还应保持同步产品[{1}}或a更改。

答案 1 :(得分:1)

我想不出一个班轮来做那件事。

from functools import reduce
mylist = {'a' : 2, 'b' : 3}
mylist["product"] = reduce(lambda x,y: x*y, mylist.values())

答案 2 :(得分:1)

您可以使用函数指定字典中所需的键,并使用inspect在运行时查看签名:

import inspect
a = 2
b = 3
def get_list(a, b, product):
   pass

mylist = inspect.getcallargs(get_list, a, b, a*b)

输出:

{'a': 2, 'product': 6, 'b': 3}

在这种情况下使用函数的好处是,您可以构建一个解决方案,以便在代码中的其他潜在对象周围查找mylist