Assume you have a list
假设你有一个清单
a = [3,4,1]
I want with this information to point to the dictionary:
我想用这些信息指向字典:
b[3][4][1]
Now, what I need is a routine. After I see the value, to read and write a value inside b's position.
现在,我需要的是例程。在我看到值之后,在b的位置读取和写入一个值。
I don't like to copy the variable. I want to change variable b's content directly.
我不喜欢复制变量。我想直接更改变量b的内容。
3 个解决方案
#1
12
Assuming b
is a nested dictionary, you could do
假设b是嵌套字典,你可以这样做
reduce(dict.get, a, b)
to access b[3][4][1]
.
访问b [3] [4] [1]。
For more general object types, use
对于更一般的对象类型,请使用
reduce(operator.getitem, a, b)
Writing the value is a bit more involved:
写这个值有点复杂:
reduce(dict.get, a[:-1], b)[a[-1]] = new_value
All this assumes you don't now the number of elements in a
in advance. If you do, you can go with neves' answer.
所有这些假设您现在没有事先提供的元素数量。如果你这样做,你可以用neves的答案。
#2
2
This would be the basic algorithm:
这将是基本算法:
To get the value of an item:
要获取项目的值:
mylist = [3, 4, 1]
current = mydict
for item in mylist:
current = current[item]
print(current)
To set the value of an item:
要设置项目的值:
mylist = [3, 4, 1]
newvalue = "foo"
current = mydict
for item in mylist[:-1]:
current = current[item]
current[mylist[-1]] = newvalue
#3
1
Assuming the list length is fixed and already known
假设列表长度是固定的并且已经知道
a = [3, 4, 1]
x, y, z = a
print b[x][y][z]
you can put this inside a function
你可以将它放在一个函数中
#1
12
Assuming b
is a nested dictionary, you could do
假设b是嵌套字典,你可以这样做
reduce(dict.get, a, b)
to access b[3][4][1]
.
访问b [3] [4] [1]。
For more general object types, use
对于更一般的对象类型,请使用
reduce(operator.getitem, a, b)
Writing the value is a bit more involved:
写这个值有点复杂:
reduce(dict.get, a[:-1], b)[a[-1]] = new_value
All this assumes you don't now the number of elements in a
in advance. If you do, you can go with neves' answer.
所有这些假设您现在没有事先提供的元素数量。如果你这样做,你可以用neves的答案。
#2
2
This would be the basic algorithm:
这将是基本算法:
To get the value of an item:
要获取项目的值:
mylist = [3, 4, 1]
current = mydict
for item in mylist:
current = current[item]
print(current)
To set the value of an item:
要设置项目的值:
mylist = [3, 4, 1]
newvalue = "foo"
current = mydict
for item in mylist[:-1]:
current = current[item]
current[mylist[-1]] = newvalue
#3
1
Assuming the list length is fixed and already known
假设列表长度是固定的并且已经知道
a = [3, 4, 1]
x, y, z = a
print b[x][y][z]
you can put this inside a function
你可以将它放在一个函数中