根据同一字典中的另一个值python设置的值

时间:2016-01-18 16:57:57

标签: python list dictionary key-value

我该如何解决这个问题?

d = {
'a':3, 
'b':(d['a']*3)
}

print(d)

导致错误,因为我尝试使用字典名称设置'b'的值,显然python不喜欢这样。我该如何解决这个问题?

此外:

l = [[2], [(l[0][0]*2)]]

print(l)

有同样的问题。

2 个答案:

答案 0 :(得分:4)

鉴于赋值如何工作 - 首先对RHS表达式进行eval'd,然后才将结果对象绑定到LHS - 这是预期的:你不能引用当前尚未创建的名称范围。

解决方案要么使用中间变量作为要重用的值,如lambo的答案中所述,要么首先使用第一个键构建jQuery.fn.extend({ /** * @description Enter your description here * @param {type} arg Use this for arguments * @param {type} arg2 Multiple if using multiple args * @return {type} Return type */ Each: function(arg, arg2) { } }); (或dict或其他)或索引/值对然后构建另一个,即:

list

答案 1 :(得分:2)

首先将值分配给变量:

x = 3
d = {'a': x, 'b': x*3}

y = 2
l = [[y], [y*2]]