Dynamic variable names
steve at holdenweb.com
Sun Feb 7 14:31:24 CET 2010
R (Chandra) Chandrasekhar wrote:
> Dear Folks,
> I have read that one should use a dictionary in python to accommodate
> dynamic variable names. Yet, I am puzzled how to achieve that in my
> case. Here is what I want to do:
> 1. The user inputs a number of six-digit hex numbers as a
> comma-separated list. These numbers represent colours, but the number of
> colours is not known beforehand.
> 2. Using these colours in pairs, I am generating image files whose names
> must be unique. I could use the respective hex numbers for this, but
> would like to explore generating filenames like
> Because I do not know how many colours there would be in advance, I need
> to generate the colour_n names on the fly.
> So, my two questions are:
> 1. How do I do this properly in python?
> 2. If there is a better scheme than what I have outlined, can someone
> please point me to a Web link?
Here's one way, though not necessarily the best:
>>> import itertools
>>> ctr = itertools.count(1)
>>> for i in range(5):
... print "colour_%03d-colour%03d.jpg" % (ctr.next(), ctr.next())
I zero-filled the names so they sort in numerical order. If this isn't a
requirement then simply change the format string to
Steve Holden +1 571 484 6266 +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010 http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS: http://holdenweb.eventbrite.com/
More information about the Python-list