Python:在初始化步骤中创建字典元素作为现有元素的修改值

问题描述 投票:0回答:4

有什么方法可以实现类似的目标:

test = {
    'x' : 1,
    'y' : test.get(x) + 1 }

这显然会失败,因为“测试”不存在。

python python-2.7 dictionary
4个回答
0
投票
# solution #1
test = {"x" : 1}
test["y"] = test["x"] + 1

# solution #1.1
test = {"x" : 1}
test.update(y=test["x"] + 1)

# solution #2
x = 1
test = {"x": x, "y": x+1}

# solution #3
# (will obviously break as soon as you want to use a callable as value...)

def yadda(**kw):
    d = kw
    for k, v in kw.items():
        if callable(v):
            d[k] = v(d)
    return d

test = yadda(x=1, y=lambda d: d["x"] + 1)

# solution #4 - attempt at making #3 more robust

class lazy(object):
    def __init__(self, f):
        self.f = f
    def __call__(self, d):
        return self.f(d) 

def yadda(**kw):
    d = kw
    for k, v in kw.items():
        if isinstance(v, lazy):
            d[k] = v(d)
    return d

test = yadda(x=1, y=lazy(lambda d: d["x"] + 1))

0
投票

从你的评论看来你想要这个:

x = 'verylongline'
suffix = 'some suffix'

test = {
    'x' : x,
    'y' : x + suffix }

0
投票
test['y'] = test['x'] + 1

如果您想在 x 更新时更改 y 的值,那么您必须在 def 中使用此代码,并在 x 更新时调用 def


0
投票

在 Python 3.8 及更高版本中,有一个针对此类情况的功能 - 赋值表达式

test = {
    'x' : (x_val := 1),  # this can be something complex, 
                         # like function call or whatever
    'y' : x_val + 1,
}

所以基本上,您将“x”的值分配给某个变量,然后使用它。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.