简体   繁体   English

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

[英]Python: create dictionary element as modified value of existing element at initialization step

Is there any way to achieve something like: 有什么办法可以实现以下目标:

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

This will obviously fail, because 'test' doesn't exist. 显然,这将失败,因为“测试”不存在。

# 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))

From your comment it seems that you want this: 从您的评论看来,您想要这样做:

x = 'verylongline'
suffix = 'some suffix'

test = {
    'x' : x,
    'y' : x + suffix }
test['y'] = test['x'] + 1

如果要在x更新时更改y的值,则必须在def中使用此代码,并在x更新时调用def

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

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