如何为列表中的大量值创建自动变量。对于前。列出 50 个值 我们如何为 50 个不同的变量赋值

How to create automatic variables for large number of values in list. For ex. list with 50 values how can we assign values to 50 different variables

例如,我们如何将大量不同的变量分配给大量列表值。 x1、x2、x3 直到 xn。

您可以使用 exec,它会在运行时计算一个字符串,然后在您键入它时执行它。将它与 format 说明符和字符串连接结合起来,你就有了>

s = ""
for i in range(0,10):
    s+="x{0} = mylist[{0}]\n".format(i)

mylist = [i*i for i in range(10)]
exec(s)

相当于手动输入:

x0 = mylist[0]
x1 = mylist[1]
x2 = mylist[2]
x3 = mylist[3]
x4 = mylist[4]
x5 = mylist[5]
x6 = mylist[6]
x7 = mylist[7]
x8 = mylist[8]
x9 = mylist[9]

然后你可以这样测试它:

p = ""
for i in range(10):
    p+="print(\"x{0} = \",x{0})\n".format(i)
exec(p)       

这给你:

x0 =  0
x1 =  1
x2 =  4
x3 =  9
x4 =  16
x5 =  25
x6 =  36
x7 =  49
x8 =  64
x9 =  81

但是,引用 this answer

the first step should be to ask yourself if you really need to. Executing code should generally be the position of last resort: It's slow, ugly and dangerous if it can contain user-entered code. You should always look at alternatives first, such as higher order functions, to see if these can better meet your needs.