[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:47:19 CEST 2006
On 6/5/06, Peter Jessop <pjlists at gmail.com> wrote:
>
> Thanks Andre
>
> I realise now I did not make it too clear.
> Basically the variable names are predictable but the values aren't.
I assumed that. I just recreated the list as you gave it because it was
easy :-)
Maybe I should have expressed it like this
>
> f0_n = "arbitrayValue"
> f0_v ="another valule"
> f1_n="something else"
> f1_v="etc.."
> ...
>
> f100_n = "another value"
> f100_v = "nexvalue"
>
> I then wish to pass the list of 2ples as an argument to a function and
> thus I need the variable themselves and not the string values.
Ok, the approach I gave you would produce instead:
data = [ ("arbitraryValue", "another valule"), ("something else", .... ]
Why couldn't you pass this to your function?
Ok, here's another experiment...
1. I will first generate a whole bunch of arbitrary numerical values:
import random
for i in range(101):
print 'f%d_n = %d'%(i, random.randint(0, 100))
print 'f%d_v = %d'%(i, random.randint(0, 100))
===
f0_n = 40
f0_v = 28
f1_n = 49
f1_v = 5
...
====================
2. Next, I will use the approach I gave you before, but with these values,
and I will do it with a one-liner:
data = '[' + ','.join(["(f%d_n, f%d_v)"%(i, i) for i in range(101)]) + ']'
big_list = eval(data)
3. Next, I will define a function that works on these values
def find_special(data):
for item in data:
if item[0] < 10:
print item[1],
find_special(big_list)
=========
The result in my case turns out to be:
49 50 57 96 98 23 69 16 4
====================
Of course this result on its own is meaningless :-)
Nonetheless, does this help? Or do you really, absolutely need to pass the
named variables, not their values?
André
_______________________________________________
> 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/9df13d9e/attachment.html
More information about the Tutor
mailing list