【问题标题】:For loop to print variable in Python [duplicate]For循环在Python中打印变量[重复]
【发布时间】:2018-10-18 12:11:48
【问题描述】:

我想在 Python 3 中打印变量 vector1 和 vector2,而不必手动编写打印代码。我怎样才能做到这一点?您可以在下面看到我尝试使用的代码。

vectorInput = input("Enter vectors values separated by ',' and vectors separated by ' ': ")

vector1,vector2 = vectorInput.split(" ")

for num in range(1,3):
    print({}.format('vector'+num))

谢谢。

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    嗯,你可以直接使用推导式。

    [print(i) for i in vectorInput.split(" ")]
    

    或者使用list的向量,因为它更适合你的使用模式,你可以在以后重用它。

    vectors = vectorInput.split(" ")
    [print(i) for i in vectors]
    

    或者for

    vectors = vectorInput.split(" ")
    for i in vectors:
        print(i)
    

    【讨论】:

      【解决方案2】:

      这是较短的版本尝试一下。

      for i in input("Enter vectors values separated by ',' and vectors separated by ' ': ").split():
          print(f'vector {i}') 
      

      如果您希望 i 为整数,则将 i 替换为 int(i)

      【讨论】:

      • 注意:这种使用fstring的方法只适用于python > 3.6。
      • 没错。 @Marcel,您也可以使用 print('vector {0}'.format(i))。
      猜你喜欢
      • 1970-01-01
      • 2018-02-04
      • 2013-03-28
      • 2015-12-29
      • 2020-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-24
      相关资源
      最近更新 更多