Search code examples
pythonvpython

Manipulating a list to increase code efficiency, struggling


from visual import *

planet = ['merc','venus','earth','mars','jupiter','saturn','uranus','neptune']
planetv = [2, 3, 4, 5, 6, 7, 8, 9]
planetp = [10, 20, 30, 40, 50, 60, 70, 80]

Essentially, I want to create new variables that are as follows:

merc.m = 2
venus.m = 3
earth.m = 4

...

merc.p = 10
venus.p = 20
earth.p = 30

...

Without changing the planet list, as I will need to access 'merc', 'venus', etc. later in the code.


Solution

  • If I understood you correctly, you want to create global variables with the names given by the list planet, with each variable bound to an object that has attributes m and p, set to the values in the lists planetv and planetp, respectively.

    If this is correct, here is a way to do it:

    # Create a class to represent the planets.  Each planet will be an
    # instance of this class, with attributes 'm' and 'p'.
    class Planet(object):
        def __init__(self, m, p):
            self.m = m
            self.p = p
    
    # Iterate over the three lists "in parallel" using zip().
    for name, m, p in zip(planet, planetv, planetp):
        # Create a Planet and store it as a module-global variable,
        # using the name from the 'planet' list.
        globals()[name] = Planet(m, p)
    

    Now you can do:

    >>> merc
    <__main__.Planet instance at 0x...>
    >>> merc.m
    2
    >>> merc.p
    10