迭代列表并在Python中为变量赋值

时间:2015-07-30 09:32:27

标签: python list python-2.7 variables differential-equations

所以我目前正在研究代码,它解决了简单的差异问题。现在我的代码看起来像这样:

deff diff():
coeffs = []
#checking a rank of a function
lvl = int(raw_input("Tell me a rank of your function: "))
if lvl == 0:
    print "\nIf the rank is 0, a differential of a function will always be 0"
#Asking user to write coefficients (like 4x^2 - he writes 4)
for i in range(0, lvl):
    coeff = int(raw_input("Tell me a coefficient: "))
    coeffs.append(coeff)
#Printing all coefficients
print "\nSo your coefficients are: "
for item in coeffs:
    print item  

接下来我想做什么?我的coeffs []列表中有每个系数。所以现在我想从那里拿出每一个并将它分配给另一个变量,只是为了利用它。我怎么能这样做?我想我将不得不使用循环,但我试图这样做几个小时 - 没有什么帮助我。那么,我怎么能这样做?这就像:a=coeff[0], b = coeff[1], ..., x = coeff[lvl]

4 个答案:

答案 0 :(得分:0)

如果你真的想要为变量分配一个列表,你可以通过访问globals() dict来实现。例如:

for j in len(coeffs):
     globals()["elm{0}".format(j)] = coeffs[j]

然后,您将在全局变量elm0elm1等中获得系数。

请注意,这很可能不是你真正想要的(但只是你要求的)。

答案 1 :(得分:0)

只需通过索引直接从列表中访问系数。

如果您想要在不同的上下文中使用值,这些值需要更改值,但您希望保持原始列表不变,则将列表复制到新列表,

import copy

mutableCoeffs = copy.copy(coeffs)

答案 2 :(得分:0)

您不需要新的变量。

您已经拥有了计算导数函数系数所需的一切。

print "Coefficients for the derivative:"
l = len(coeffs) -1
for item in coeffs[:-1]:
    print l * item
    l -=1

或者如果您想将它们放入新列表中:

deriv_coeffs = []
l = len(coeffs) -1
for item in coeffs[:-1]:
    deriv_coeffs.append(l * item)
    l -=1

答案 3 :(得分:0)

我想从那里你想要区分不?所以你只需将它排名的cofficient时间分配给index-1?

deff diff():

    coeffs = []
    #checking a rank of a function
    lvl = int(raw_input("Tell me a rank of your function: "))
    if lvl == 0:
        print "\nIf the rank is 0, a differential of a function will always be 0"
    #Asking user to write coefficients (like 4x^2 - he writes 4)
    for i in range(0, lvl):
        coeff = int(raw_input("Tell me a coefficient: "))
        coeffs.append(coeff)
    #Printing all coefficients
    print "\nSo your coefficients are: "
    for item in coeffs:
        print item  
    answer_coeff = [0]*(lvl-1)
    for i in range(0,lvl-1):
        answer_coeff[i] = coeff[i+1]*(i+1)
    print "The derivative is:"
    string_answer = "%d" % answer_coeff[0]
    for i in range(1,lvl-1):
        string_answer = string_answer + (" + %d * X^%d" % (answer_coeff[i], i))
    print string_answer