如何使用嵌套循环遍历不同的词典?
How can I go through different dictionaries using nested loop?
sem1_credit = {'A': 4, 'B': 4, 'C': 3}
sem2_credit = {'D': 5, 'E': 1}
sem3_credit = {'F': 3}
e = 2
for j in range(e):
for i in 'sem'+str(j+1)+'_credit':
我想使用循环访问不同的字典。所以我尝试使用循环创建带有连接的字典名称。但它不起作用。有没有办法解决这个问题,或者有其他方法可以在没有循环的情况下处理字典。
调用locals()
可以获得当前局部符号table的字典。所以 locals()['sem1_credit']
本质上就是这个 sem1_credit
.
从这里开始,您可以构建一个循环:
sem1_credit = {'A': 4, 'B': 4, 'C': 3}
sem2_credit = {'D': 5, 'E': 1}
sem3_credit = {'F': 3}
for idx in range(1, 4):
credits = locals()[f'sem{idx}_credit']
for key, credit in credits.items():
print(f"{key} {credit}")
请记住,range(num)
生成从 0 到 num-1 的数字。所以在你的代码中,range(2)
只生成 0 和 1。
sem1_credit = {'A': 4, 'B': 4, 'C': 3}
sem2_credit = {'D': 5, 'E': 1}
sem3_credit = {'F': 3}
e = 2
for j in range(e):
for i in 'sem'+str(j+1)+'_credit':
我想使用循环访问不同的字典。所以我尝试使用循环创建带有连接的字典名称。但它不起作用。有没有办法解决这个问题,或者有其他方法可以在没有循环的情况下处理字典。
调用locals()
可以获得当前局部符号table的字典。所以 locals()['sem1_credit']
本质上就是这个 sem1_credit
.
从这里开始,您可以构建一个循环:
sem1_credit = {'A': 4, 'B': 4, 'C': 3}
sem2_credit = {'D': 5, 'E': 1}
sem3_credit = {'F': 3}
for idx in range(1, 4):
credits = locals()[f'sem{idx}_credit']
for key, credit in credits.items():
print(f"{key} {credit}")
请记住,range(num)
生成从 0 到 num-1 的数字。所以在你的代码中,range(2)
只生成 0 和 1。