【问题标题】:Using a loop to create and assign multiple variables (Python) [duplicate]使用循环创建和分配多个变量(Python)[重复]
【发布时间】:2017-05-29 11:48:08
【问题描述】:

我希望使用 for 循环创建多个变量,在迭代 (i) 中命名,并为每个变量分配一个唯一的 int。

Xpoly = int(input("How many terms are in the equation?"))


terms={}
for i in range(0, Xpoly):
    terms["Term{0}".format(i)]="PH"

VarsN = int(len(terms))
for i in range(VarsN):
    v = str(i)
    Temp = "T" + v
    Var = int(input("Enter the coefficient for variable"))
    Temp = int(Var)

正如你在最后看到的,我迷路了。理想情况下,我正在寻找一个输出,其中

T0 = #
T1 = #
T... = #
T(Xpoly) = #

有什么建议吗?

【问题讨论】:

  • 使用字典代替变量 T0, T1 。代码Temp = "T" + v 不会创建名称为T0T1 的变量,而只会创建文本"T0""T1",您可以在字典terms[Temp] = Var 中使用它
  • 顺便说一句:对变量和函数使用 lower_case 名称 - vars_ntempvar - 它使代码更具可读性,因为我们仅对类使用 CamelCase 名称。跨度>
  • 您可以使用一个 for 循环 - 与 terms["Term{0}".format(i)] = var
  • 如果有人来到这里并想要完全实现作者所描述的内容,请使用this

标签: python loops for-loop while-loop


【解决方案1】:

你可以在一个循环中完成所有事情

how_many = int(input("How many terms are in the equation?"))

terms = {}

for i in range(how_many):
    var = int(input("Enter the coefficient for variable"))
    terms["T{}".format(i)] = var 

以后你可以使用

 print( terms['T0'] )

但使用列表可能比字典更好

how_many = int(input("How many terms are in the equation?"))

terms = [] # empty list

for i in range(how_many):
    var = int(input("Enter the coefficient for variable"))
    terms.append(var)

以后你可以使用

 print( terms[0] )

甚至(获得前三个术语)

 print( terms[0:3] )

【讨论】:

  • range(how_many+1)。这是我从他的问题中理解的。 range(0, Xpoly) 他想要T(Xpoly)
  • 也许T(Xpoly) 建议how_many+1range(0, Xpoly) 仅表示how_many - 从0how_many-1(从0Xpoly-1
猜你喜欢
  • 2016-03-07
  • 1970-01-01
  • 1970-01-01
  • 2020-09-06
  • 1970-01-01
  • 2022-01-22
  • 1970-01-01
  • 2017-04-06
相关资源
最近更新 更多