假设我有以下列表:
abcd = [random.uniform(-10,10) for n in range(4)]
与结果
abcd = [-1.3040458562760016, 1.142558074067301, 1.8875155690248278, -9.876512891278184]
我想让a = abcd[0],b=abcd[1]
…有没有更好更快的方法?谢谢!
a, b, c, *rest = [1, 2, 3, 4, 5, 6, 7, 8]
print(a, b, c, rest)
为
1 2 3 [4, 5, 6, 7, 8]
所以在你的例子中只需:
a, b, c, d = [random.uniform(-10,10) for n in range(4)]
我想你可以这样做:
exec(';'.join('{}={}'.format(x, abcd[i]) for i, x in enumerate('abcd')) )
,但是所有关于使用exec
的通常警告都适用。你确定要这么做吗?
或者您可以在alphabet
中为every letter
生成a variable
:
# alphabet a-z
from string import ascii_lowercase
# random function
from random import uniform
alpha = ascii_lowercase # short name
variables = ", ".join(list(alpha)) # variables list
values = [uniform(-10, 10) for _ in range(len(alpha))] # list comp for values
code = "{} = {}".format(variables, values) # generating the string
print(code) # printing string
exec(code) # executing string
输出,这是executed
:
a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z = [
-5.661884131346637,
-2.056351741196769,
-5.58762656617713,
-1.6853783801622146,
7.219790611016201,
-9.444645344272267,
4.735088207619203,
-3.8262971416955853,
-4.028608365004676,
9.873826688967224,
4.8023159243404905,
-6.545978360634413,
3.540237342634887,
5.366084302814462,
3.1646338425404217,
-8.294347963969429,
-5.100975456579803,
-4.993281347287077,
-2.771922255860922,
5.179076193360736,
-3.4112710072609964,
-8.280142716192692,
5.372558876910256,
-1.3829611354128435,
7.613945718558888,
-8.83924323952356
]
访问a
:
>>> a
-5.661884131346637
也可以使用*unpacking
将变量的数量分配给grow
到infinty
。