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

时间:2015-09-18 10:17:18

标签: python python-2.7 dictionary

有没有办法实现类似的目标:

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

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

3 个答案:

答案 0 :(得分: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))

答案 1 :(得分:0)

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

x = 'verylongline'
suffix = 'some suffix'

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

答案 2 :(得分:0)

test['y'] = test['x'] + 1

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