Re: Dynamic variable names

Discussion in 'Python' started by Steve Holden, Feb 7, 2010.

  1. Steve Holden

    Steve Holden Guest

    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
    >
    > colour_1-colour_2.jpg
    >
    > 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())
    ....
    colour_001-colour002.jpg
    colour_003-colour004.jpg
    colour_005-colour006.jpg
    colour_007-colour008.jpg
    colour_009-colour010.jpg
    >>>


    I zero-filled the names so they sort in numerical order. If this isn't a
    requirement then simply change the format string to

    "colour_%d-colour%d.jpg"

    regards
    Steve
    --
    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/
    Steve Holden, Feb 7, 2010
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Replies:
    2
    Views:
    8,287
    cesarjusto
    Jul 15, 2010
  2. wanwan
    Replies:
    3
    Views:
    429
    Alex Martelli
    Oct 14, 2005
  3. News123
    Replies:
    2
    Views:
    463
    John Machin
    Nov 26, 2008
  4. Ken Halley

    Dynamic Variable Names - Syntax?

    Ken Halley, Nov 6, 2003, in forum: ASP General
    Replies:
    5
    Views:
    201
    Ray at
    Nov 7, 2003
  5. Peter Buckley
    Replies:
    5
    Views:
    198
    matt neuburg
    Feb 27, 2009
Loading...

Share This Page