[Tutor] Fwd: What's in a name?

Keith Winston keithwins at gmail.com
Fri Jan 3 07:18:55 CET 2014


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
                ))

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.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20140103/f9a18544/attachment.html>


More information about the Tutor mailing list