简体   繁体   中英

how to increase variable name in Python?

I'm making a simulation program.

I manually write some initial conditions of particles with python list before starting program, such as

var1 = [mass_a, velocity_a, velocity_a]
var2 = [mass_b, velocity_b, velocity_b]
...

then how do I change that number in variable in for loop? Something I tried was

for i in range(2):
    print(var+str(i)) 

but they don't work

Always remember

If you ever have to name variables suffixed by numbers as in your example, you should consider a sequential indexable data structure like array or list. In Python to create a List we do

var = [[mass_a, velocity_a, velocity_a],
       [mass_b, velocity_b, velocity_b]]

If you ever have to name variables with varying suffixes like

var_A=[mass_a, velocity_a, velocity_a]

var_B=[mass_b, velocity_b, velocity_b]

you should consider a non-sequential indexable data structure like hashmap or dictionary. The key of this dictionary should be the varying suffix and the values should be the values assigned to the respective variable In Python to create a dictionary we do

var = {'A':[mass_a, velocity_a, velocity_a],
       'B':[mass_b, velocity_b, velocity_b]}

Could you put your variables var1, var2, ... into a list and iterate through the list, instead of relying upon numbered variable names?

Example:

vars = [var1, var2]

for var in vars:
    do_something(var)

Just to be the devil's advocate here, you can make this approach work as below.

for i in range(2):
    print( globals()["var"+str(i+1)] )

You can put your variables in a list and iterate on it like,

var_list = [var_a,var_b...]

for var in var_list:
    print var

Alternatively, you can put the your variables in a dictionary like,

var_dict = {"var_a":var_a,"var_b":var_b,...}

for var in var_dict:
  print var_dict(var)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM