如果您真的想这样做,您将不得不通过存储在另一个变量中的名称来访问这些变量。有人称其为“动态变量名”。如果您再次真的想要这样做,一种选择是使用globals():
for x in ['A', 'B', 'C']:
print(f'The value of the model {x} is:', globals()[x + '_PR'])
# The value of the model A is: 3
# The value of the model B is: 4
# The value of the model C is: 6
但不推荐:见How do I create variable variables?。
因此,更好的选择之一可能是使用可迭代的数据类型,例如dict:
models = {'A': 3, 'B': 4, 'C': 6}
for x in ['A', 'B', 'C']:
print(f'The value of the model {x} is: {models[x]}')
如果我想保留订单,可以使用items 进一步简化它,虽然我不是这个的忠实粉丝。
models = {'A': 3, 'B': 4, 'C': 6}
for k, v in models.items():
print(f'The value of the model {k} is: {v}')
(dict 确实保留了顺序,但在我看来,我认为 dict 在概念上没有被排序)。