Nic*_*ick 1 python variables automation nested
基本上,我需要让我的程序能够为我创建多个(无限制)变量,我仍然可以通过我的代码使用操作,而不需要我定义它们.
我想将一个字母和一个数字作为变量名称,例如a1,并让程序创建新变量,只需在数字中加1即可.所以它会创建a1到a30左右.我该怎么做?
我的程序将添加多项式,并且变量(或现在列表)是用于分隔不同的单项式,并且由于我不知道多项式中将存在多少单项式,我需要一种方法来使数字灵活,所以我对于单项式有一个确切的空间,没有额外的,也没有更少.
这是代码:
# Sample polynomial set to x, the real code will say x = (raw_input("Enter a Polynomial")).
x = '(5xx + 2y + 2xy)+ (4xx - 1xy)'
# Isdigit command set to 't' to make the code easier to write.
t = str.isdigit
# Defining v for later use.
v = 0
# Defining 'b' which will be the index number that the program will look at.
b = 1
# Creating 'r' to parse the input to whatever letter is next.
r = x [b]
# Defining n which will be used later to tell if the character is numeric.
n = 0
# Defining r1 which will hold one of the monomials, ( **will be replaced with a list**)
#This was the variable in question.
r1 = ''
# Setting 'p' to evaluate if R is numeric ( R and T explained above).
p = t(r)
# Setting 'n' to 1 or 0 to replace having to write True or False later.
if p == True:
n = 1
else:
n = 0
# Checking if r is one of the normal letters used in Algebra, and adding it to a variable
if r == 'x':
v = 'x'
c = 1
elif r == 'y':
v = 'y'
c = 1
elif r == 'z':
v = 'z'
c = 1
# If the character is a digit, set c to 0, meaning that the program has not found a letter yet (will be used later in the code).
elif n == 1:
v = r
c = 0
# Adding what the letter has found to a variable (will be replaced with a list).
r1 = r1 + v
b = b + 1
Run Code Online (Sandbox Code Playgroud)
我最终会把它变成一个循环.
我在代码中添加了注释,因此更容易理解.
本质上,您正在尝试以编程方式动态修改变量所在的堆空间.我真的不认为这是可能的.如果是,那就非常模糊.
我确实知道你来自哪里.当我第一次学习编程时,我曾想过以需要这种"动态创建"变量的方式解决问题.解决方案实际上是识别哪种(集合)数据结构符合您的需求.
如果要a1通过变量a30,请创建一个列表a.那a1将是a[1],a30将是a[30].写入有点不同,但它应该为您提供所需的行为.
| 归档时间: |
|
| 查看次数: |
416 次 |
| 最近记录: |