使用循环创建和分配多个变量(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屋!
查看全文