python如何取动态变量名的值?
程序结构大体如下
tree_1={...}
tree_2={...}
...
tree_n={...}
如何通过for循环取出以上变量,并遍历
for i in range(1,n):
for item in tree_i: 关键是这个tree_i如何搞
回答:
python">tree_1 = {'a1': 1, 'a2': 2}tree_2 = {'a3': 3, 'a4': 4}
tree_3 = {'a5': 5, 'a6': 6}
for i in range(1, 4):
value = eval(f'tree_{i}')
for item in value:
print(item, value[item])
或者
tree_1 = {'a1': 1, 'a2': 2}tree_2 = {'a3': 3, 'a4': 4}
tree_3 = {'a5': 5, 'a6': 6}
for i in range(1, 4):
value = locals()[f'tree_{i}']
for item in value:
print(item, value[item])
回答:
推荐方法1:
trees = { 'tree_1': {...},
'tree_2': {...},
# ...
'tree_n': {...},
}
for i in range(1, n+1):
tree = trees[f'tree_{i}']
for item in tree:
#
方法二三:
for i in range(1, n+1): tree = locals()[f'tree_{i}']
for item in tree:
或者
for i in range(1, n+1): tree = globals()[f'tree_{i}']
for item in tree:
以上是 python如何取动态变量名的值? 的全部内容, 来源链接: utcz.com/p/939004.html