I have a string say
s = ['799.58812', '437.90386', '282.94545', '1.8511', '6.31', '-0.2928', '0.0687', '0.3615', '19.0002', '0.021375', '-76.404702', '-76.401867', '-76.400922', '-76.422349', '6.002']
Now I want to store each value in a separate variable.
I know it can be done by simply p1 = float(s.split()[1]).
But I want something like based on length the new variables should get created automatically and store the values
example:
p1 = 799.58812
p2 = 437.90386
p3 = 282.94545
....
....
....
p15 = 6.002
Can any one tell me how to do this in python ?
3 Answers 3
It's bad idea to do such things, it would be better to use iteration on s, but if you want:
for n, value in enumerate(s, start=1):
globals()["p%d"%n] = float(value)
1 Comment
You can use globals() to achieve the goal, ie.
s = ['799.58812', '437.90386', '282.94545', '1.8511', '6.31', '-0.2928', '0.0687', '0.3615', '19.0002', '0.021375', '-76.404702', '-76.401867', '-76.400922', '-76.422349', '6.002']
for index, item in enumerate(s):
globals()['p%s' % (index+1)] = float(item)
which will yield variables named p1...p15, or alternatively, and my preferred way would be to put them in your own dictionary.
sdict = dict(('p%s' % (index+1), item) for index, item in enumerate(s))
print sdict
{'p1': '799.58812',
'p10': '0.021375',
'p11': '-76.404702',
'p12': '-76.401867',
'p13': '-76.400922',
'p14': '-76.422349',
'p15': '6.002',
'p2': '437.90386',
'p3': '282.94545',
'p4': '1.8511',
'p5': '6.31',
'p6': '-0.2928',
'p7': '0.0687',
'p8': '0.3615',
'p9': '19.0002'}
Comments
Method 1 (The worst way):
As others have mentioned, you can achieve what you're trying to do with globals() or the slightly safer locals()
However, I would highly suggest that you don't do that. It's bad coding practice. If you can't type it out by hand in the first place, why do you need to be able to type it out by hand? There really isn't a reason that you would need to have the value as a local variable, especially considering that all you're doing by adding it to globals/locals is essentially adding it to another dictionary.
Method 2: Leave it as it
What's wrong with leaving it as it is? It's this:
s[1]
vs
p1
Method 3: Use a dictionary
numbers = {"p{}".format(i):s[i] for i in range(len(s)}
then
numbers["p1"]
Method 4: Getattr method
If you REALLY need to have the shorthand, I would suggest a class with a getattr set and you can name anything you want to be convenient Something like. Just remember that methods cannot start with an number:
class MyClass(object):
def __init__(self, lst):
self.s = lst
def __getattr__(self, name):
try:
return self.s[int(name[1:])]
except:
raise AttributeError()
and you would use it like this:
x = MyClass(s)
x.p1
and you would use it like this:
Method 5: Python Magic!
Use a combination of the property class, a metaclass, and the new magic method. This is overkill but at least you learn a nice trick in python.
s = ['799.58812', '437.90386', '282.94545', '1.8511', '6.31', '-0.2928', '0.0687', '0.3615', '19.0002', '0.021375', '-76.404702', '-76.401867', '-76.400922', '-76.422349', '6.002']
def create_property(index):
def getr(self):
return s[index]
def setr(self, value):
s[index] = value
def delr(self):
raise AttributeError("Cannot delete this field")
return property(getr, setr, delr)
class PropertyCreatorClass(type):
def __new__(mcs, clsname, bases, dct):
for i in range(len(s)):
dct["p{}".format(i)] = create_property(i)
return type.__new__(mcs, clsname, bases, dct)
class SClassRep(object):
__metaclass__ = PropertyCreatorClass
Here's how you would use it.
x = SClassRep()
x.p1
s[0] = 799.58812 s[1] = 437.90386 s[2] = 282.94545