假设你有一个清单
a = [3,4,1]
我想用这些信息来指向字典:
b[3][4][1]
现在,我需要的是例行公事。看到该值后,在 b 的位置内读取和写入一个值。
我不喜欢复制变量。我想直接改变变量b的内容。
假设
b
是一个嵌套字典,你可以这样做
reduce(dict.get, a, b)
访问
b[3][4][1]
。
对于更通用的对象类型,请使用
reduce(operator.getitem, a, b)
写入值有点复杂:
reduce(dict.get, a[:-1], b)[a[-1]] = new_value
所有这些都假设您现在不提前知道
a
中的元素数量。如果你这样做,你可以接受neves的回答。
这将是基本算法:
获取物品的价值:
mylist = [3, 4, 1]
current = mydict
for item in mylist:
current = current[item]
print(current)
设置项目的值:
mylist = [3, 4, 1]
newvalue = "foo"
current = mydict
for item in mylist[:-1]:
current = current[item]
current[mylist[-1]] = newvalue
假设列表长度是固定的并且已知
a = [3, 4, 1]
x, y, z = a
print b[x][y][z]
你可以把它放在一个函数中
让我们编写自己的
getnesteditem
和setnesteditem
:
def getnesteditem(xs, path):
for i in path:
xs = xs[i]
return xs
def setnesteditem(xs, path, newvalue):
for i in path[:-1]:
xs = xs[i]
xs[path[-1]] = newvalue
并尝试使用您的索引列表
a = [3,4,1]
:
a = [3, 4, 1]
b = [[[15*i+3*j+k for k in range(3)] for j in range(5)] for i in range(4)]
print(*b, sep='\n')
# [[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8], [ 9, 10, 11], [12, 13, 14]]
# [[15, 16, 17], [18, 19, 20], [21, 22, 23], [24, 25, 26], [27, 28, 29]]
# [[30, 31, 32], [33, 34, 35], [36, 37, 38], [39, 40, 41], [42, 43, 44]]
# [[45, 46, 47], [48, 49, 50], [51, 52, 53], [54, 55, 56], [57, 58, 59]]
print(getnesteditem(b, a))
# 58
setnesteditem(b, a, -9)
print(*b, sep='\n')
# [[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8], [ 9, 10, 11], [12, 13, 14]]
# [[15, 16, 17], [18, 19, 20], [21, 22, 23], [24, 25, 26], [27, 28, 29]]
# [[30, 31, 32], [33, 34, 35], [36, 37, 38], [39, 40, 41], [42, 43, 44]]
# [[45, 46, 47], [48, 49, 50], [51, 52, 53], [54, 55, 56], [57, -9, 59]]