【问题标题】:Someones know a better option to print this variables?有人知道打印此变量的更好选择吗?
【发布时间】:2021-09-20 01:17:17
【问题描述】:

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

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 循环思考,但我无法让它工作。

【问题讨论】:

  • 请澄清您的具体问题或提供其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。

标签: python for-loop printing


【解决方案1】:

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

A_PR=3
B_PR=4
C_PR=6

print('Model A: {} \nModel B: {}\n Model C: {}'.format(A_PR, B_PR, C_PR))

或者您可以将这些值嵌入到一个数组中并在该数组上循环。使用 ASCI 值可以打印 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

【讨论】:

    【解决方案2】:
        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 stringsdictionary 提出的一个简单解决方案

    【讨论】:

      【解决方案3】:

      如果您真的想这样做,您将不得不通过存储在另一个变量中的名称来访问这些变量。有人称其为“动态变量名”。如果您再次真的想要这样做,一种选择是使用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 在概念上没有被排序)。

      【讨论】:

        【解决方案4】:

        这样的东西应该可以作为一个带有 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}')
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2022-07-08
          • 1970-01-01
          • 1970-01-01
          • 2020-08-30
          • 1970-01-01
          • 1970-01-01
          • 2013-06-05
          相关资源
          最近更新 更多