python如何取动态变量名的值?
程序结构大体如下
tree_1={...}tree_2={...}...tree_n={...}
如何通过for循环取出以上变量,并遍历for i in range(1,n):
for item in tree_i: 关键是这个tree_i如何搞
回复
1个回答

test
2024-06-27
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])
回复

适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容