On 03/01/2014 06:18, Keith Winston wrote:
Shoot: I sent this response directly to Mark, without even trimming.
Here it is to the list...
Hi Mark: sorry for unclarity. I am probably going to make a hash of
explaining this, but here goes:
I want to iterate a variable across a list of objects, and print both
the outputs (wrong word) of said objects, and the name of the objects.
Those objects might be lists, or functions, as examples.
As a non-iterative example, something like this:
a = "max"
print(eval(a)(3,4), a) # output: 4 max
That's the only way I can figure out how to make it work. Here's an
actual code snippet, watch for stype:
for func in ["mean", "max", "min", "variance", "stdev"]:
print("{moves:9.2f} {chutes:12.2f} {ladders:13.2f}
{stype}".format(
moves=eval(func)(tgset[1] for tgset in garray),
chutes=eval(func)(tgset[2] for tgset in garray),
ladders=eval(func)(tgset[3] for tgset in garray),
stype=func
))
You enjoy making life difficult for yourself :) You've assigned strings
to the name func, just assign the functions themselves? Like.
for func in max, min:
print(func.__name__, func(range(5)))
Output.
max 4
min 0
Output:
4.67 0.21 0.79 mean
28.00 1.00 1.00 max
1.00 0.00 0.00 min
23.69 0.17 0.17 variance
4.87 0.41 0.41 stdev
I appreciate the point about eval being dangerous, though the second
line in your reference does say "if you accept strings to evaluate from
untrusted input". Still, I can appreciate how eval() could go off the
rails. Is there another way I can do what I want? Sorry for not testing
the code I posted earlier.
--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.
Mark Lawrence
_______________________________________________
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor