Reputation: 4511
I found several topics where discussed that dynamical creating of single variables in loops is bad practice and better use dictionary.
In my case I don't need create them dynamically, I want access them in the loop.
I don't want to use dictionary for them, because these variables are used in lot of places in code, and only in one place I need such dynamic access.
Idea example:
car_pos = 1; man_pos = 10
car_vel = 100; man_vel = 5
for elm in ['car', 'man']:
elm_pos = elm + '_pos'
elm_vel = elm + '_vel'
# I want values of elements with such names here
print(elm_pos, elm_vel)
# Desired output:
# (1, 100)
# (10, 5)
Upvotes: 3
Views: 1377
Reputation: 184171
Variable names are a terrible way to relate pieces of information. There is nothing linking man_pos
and man_vel
except that they both happen to start with man
. Other than that they are totally separate. Python has better ways of bundling elements like these together.
In this case, man
and car
should be objects with attributes pos
and vel
.
class Thing:
def __init__(self, pos, vel):
self.pos = pos
self.vel = vel
# assume that both men and cars move only in one dimension
man = Thing(10, 2)
car = Thing(100, -5)
Then your loop is simply:
for item in [car, man]:
print(item.pos, item.vel)
Do not do it the way you're trying to do it. It will only lead to tears -- if not yours, then of the people who have to look at your code.
Upvotes: 4
Reputation: 246
Agree with everything that kindall said. However, you can try named tuple to go the non dictionary route...
from collections import namedtuple
data = namedtuple('data',('pos','vel'))
car = data(1,100)
man = data(10,5)
for elm in (car,man):
print(elm.pos,elm.vel)
Upvotes: 1
Reputation: 2130
Just use the globals() dictionary, with key as your variable names. The value for these keys would be the actual value of these variables.
car_pos = 1; man_pos = 10
car_vel = 100; man_vel = 5
for elm in ['car', 'man']:
elm_pos = elm + '_pos'
elm_vel = elm + '_vel'
print(globals()[elm_pos], globals()[elm_vel])
Upvotes: 2