有人知道打印这个变量的更好的选择吗?



我正在寻找更快地打印一些变量。我使用的代码是:

A_PR=3
B_PR=4
C_PR=6
print('the value of the model A is:', A)
print('the value of the model B is:', B)
print('the value of the model C is:', C)

我想在循环中加上for,但是我做不到。

你可以这样使用字符串格式:

A_PR=3
B_PR=4
C_PR=6
print('Model A: {} nModel B: {}n Model C: {}'.format(A_PR, B_PR, C_PR))

或者你可以将这些值嵌入到数组中并循环遍历该数组。使用ascii值可以打印A - Z模型结果

A_PR=3
B_PR=4
C_PR=6
model_results = [A_PR, B_PR, C_PR]
for idx, result in enumerate(model_results):
print('Model {}: {}'.format(chr(idx + 65), result))

输出:

Model A: 3
Model B: 4
Model C: 6
model_dict = {'A':3, 'B':4, 'C':6,}
for k,v in model_dict.items():
print(f"the value of model {k} is: {v}")

这是一个简单的解决方案,我使用python的f字符串和一个字典

如果您真的想这样做,您必须通过存储在另一个变量中的名称来访问这些变量。有些人称之为"动态变量名"。如果你真的想要这样做,一个选择是使用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

但是不建议使用:参见如何创建可变变量?

因此,更好的选择之一可能是使用可迭代的数据类型,例如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}')

(Adict确实保留了顺序,但在我看来,我认为dict在概念上不是有序的)。

这样的东西应该可以作为一个带有for循环的小字典。只需解包键和值。

PR = {
"A_PR": 3, "B_PR" :4 , "C_PR":6,
}
for k,v in PR.items():
print(f'the value of the model {k} is: {v}')

最新更新