+ 1
How to make a loop that creates variables automatically... In Python
Say u want to access data from a input but in this system u want it to automatically create variables on the results the user had in this system (I just want to know how to make something that creates variables say something like a function)
3 ответов
+ 10
Edward Marais ,
you can create variables dynamically like this:
# create variables dynamically <<<<<<<
l = [1,2,3]
for i in l:
locals()["a"+str(i)]=i ** 2 # (1)
print(f'(1) {a1}')
print(locals())
(1) creates a local variable composed from a letter 'a', but can be also an other string. a value from a list is taken to the power of 2 and assigned to the new variable
an other way of storing information dynamically is to use a dict:
d = {}
lst = [1, 3, 5, 7, 2, 4, 9]
for i in range(len(lst)):
d["var" + str(i)] = lst[i]
print(f'(2) {d}')
for i in d:
print(i, "=", d[i])
print("var0 + var1 =", d["var0"] + d["var1"])
print(locals())
in this case no "real" variables are created, but by using a dict it makes it easy to access (read / write) the values
+ 6
There is no point in dynamically creating a variable inside a loop, that's what lists, dictionaries, or other similar data types, are for.
However, if you're still interested and maybe have a specific use in mind, then you can use the exec function:
exec('a = 10') # this will create a variable named a with value 10
The previous variable will be created inside the function scope, so if you want it to be global not just inside your function, you'll have to specify that:
exec('a = 10', globals())
+ 3
variable = {}
for num in range(1,4):
variable["key%s" %num] = "abc"
print(variable)