+ 1
How to create a dynamic variable in python
name = 0 basically what it should do is : name1 = 0 name2 =0 name3 = 0 Is this possible?
12 Antworten
+ 2
Lothar Fixed.
x = 1
while x < 4:
exec("name{}={}" .format(x, x))
x += 1
If You want to test the New variables, write this before the addition:
exec("print(name{})" .format(x))
+ 5
Edward Marais ,
to do this task we can generate the variable names like *var* + a number inside a loop. then we have to add this name together with the value we like to assign to the locals() dict.
# create variables dynamically
lst = [10, 24, 37]
for ndx, i in enumerate(lst):
locals()["var"+str(ndx)]=i
print(var2)
print(locals()) # shows the locals() dict with the variables
instead of using numbers from a list, we can also use input() function.
>>> instead of using the above procedure, we can also use a list or a dictionary and store the input values in it. this makes it easier to handle the variable & and values during execution.
may be you can show us what you like to achieve so that we can recommend the best way.
thanks!
+ 3
I'm still wondering why one would not just use some container type for it, like Oma Falk suggested.
+ 2
Edward Marais ,
with the description in my post you should be able to do a test if it is possible or not.
i still believe that using data structures like list or dictionary can do what you need. but anyway it is your decision - good success!
+ 2
Luis Baroni
x = 1
while <condition>:
exec "name%s = %s" %(x) # <<< creates syntax error. can you check this?
x += 1
+ 2
Lothar The sintax error ocurred because I forgot the parentheses. :)
I change the formatting of the text to make it more understable.
+ 2
Luis Baroni ,
this looks very nice now.
+ 2
name = []
name.append(0)
name.append(1)
print(name[0])
print(name[1])
+ 2
Edward Marais ,
my last try for this post. since you still have not given more details / code samples it is still guessing for all who are trying to help you:
names = {'human1': 0, 'human2': 2, 'alien1': 3, 'human3': 1, 'human4': 0}
print(len(names)) # "variables" in total
print("number of humans", len([ctg for ctg in names.keys() if ctg.startswith("human")])) # 4
print("number of aliens", len([ctg for ctg in names.keys() if ctg.startswith("alien")])) # 1
names['alien2'] = 1
print("number of aliens", len([ctg for ctg in names.keys() if ctg.startswith("alien")])) # 2
+ 2
HonFu "[...] Python doesn't try to prevent you from shooting yourself in the foot [...]". 🙃
http://stupidpythonideas.blogspot.com/2013/05/why-you-dont-want-to-dynamically-create.html?m=1
+ 1
@Lothar basically what i want to know is if you can create a variable that can create new variables to store data for example ( Human = 0 ) and lets say it was in a for loop that runs n times that n number is how many human variables that will be created and stores data . I'm just curious if this is possible
0
Edward Marais , you should try with this:
x = 1
While <condition>:
exec "name%s = %s" %(x)
x += 1