[Tutor] Reference a variable from a string whose value is the name of the variable

Andre Roberge andre.roberge at gmail.com
Tue Jun 6 01:09:56 CEST 2006


I'm not sure if it's exactly what you need, but here's something that may
come close.

On 6/5/06, Peter Jessop <pjlists at gmail.com> wrote:
>
> The best way to explain my problem is with an example
>
> f0_n = "field0"
> f0_v ="value0"
> f1_n="field1"
> f1_v="value1"
> ...
>
> f100_n = "field100"
> f100_v = "value100"


Ok, I'm going to recreate this fake example, rather than typing it all out
:-)
for i in range(101):
    print 'f%d_n = "field%d"'%(i, i)
    print 'f%d_v = "value%d"'%(i, i)

I then cut-and-paste the result in the editor window and start again.


data1 = ["(f%d_n, f%d_v)"%(i, i) for i in range(101)]

print data1
# This shows: ['(f0_n, f0_v)', '(f1_n, f1_v)', '(f2_n, f2_v)' ... '(f100_n,
f100_v)']

data2 = ','.join(data1)
data2 = '[' + data2 + ']'
print eval(data2)

The result is: [('field0', 'value0'), ('field1', 'value1'), ...,
('field100', 'value100')]
i.e. it is a list of 2ples that contains the values of the variable, rather
than the variables themselves.  For most applications, this should be the
same thing, right?

André


I now want to define a list of 2ples of the form
>
> [(f0_n,f0_v),(f1_n,f1_v),...,(f100_n,f100_v)]
>
> I wish to define the list using a for loop, i.e.
>
> data = [ ]
> for i in xrange(1,101):
>   data = data.append((f %i  _n, f %i_v))
>
> I have put the % sign above. Obviously it is not like that but how
> does one do it?
> The aim is to reference the s variable whose name is the string that I
> create concatenating "f" + str(i)+"_n" and "f"+str(i)+"_v"
>
> Thanks
>
> Peter Jessop
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060605/15de327f/attachment.htm 


More information about the Tutor mailing list