使用循环创建和分配多个变量 (Python) [英] Using a loop to create and assign multiple variables (Python)
本文介绍了使用循环创建和分配多个变量 (Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望使用 for 循环来创建多个变量,以迭代 (i) 命名,并为每个变量分配一个唯一的 int.
I'm looking to use a for loop to create multiple variables, named on the iteration (i), and assign each one a unique 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)
正如你在最后看到的,我迷路了.理想情况下,我正在寻找一个输出
As you see at the end I got lost. Ideally I'm looking for an output where
T0 = #
T1 = #
T... = #
T(Xpoly) = #
有什么建议吗?
推荐答案
你可以在一个循环中完成所有事情
You can do everything in one loop
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'] )
但最好使用列表而不是字典
But it is probably better to a use list rather than a dictionary
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] )
甚至(获得前三个术语)
or even (to get first three terms)
print( terms[0:3] )
这篇关于使用循环创建和分配多个变量 (Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文