基本上,我需要让我的程序能够为我创建多个(无限)变量,我仍然可以在我的代码中使用这些变量,而无需我定义它们。
我想用一个字母和一个数字作为变量名,例如 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
我最终会把它变成一个循环。
我在代码中添加了注释以使其更易于理解。
请您参考如下方法:
本质上,您正在尝试以编程方式动态修改变量所在的堆空间。我真的不认为这是可能的。如果是,那是非常晦涩的。
我明白你的意思。当我第一次学习编程时,我曾想过以需要这种“动态创建”变量的方式来解决问题。真正的解决方案是识别哪种(集合)数据结构适合您的需求。
如果您想要从 a1 到 a30 的变量,请创建一个列表 a。那么a1就是a[1],a30就是a[30]。编写起来有点不同,但它应该会为您提供所需的行为。
