python - 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, want create new variables follows:

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

...

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

...

without changing planet list, need access 'merc', 'venus', etc. later in code.

if understood correctly, want create global variables names given list planet, each variable bound object has attributes m , p, set values in lists planetv , planetp, respectively.

if correct, here way it:

# create class represent planets.  each planet # instance of class, attributes 'm' , 'p'. class planet(object):     def __init__(self, m, p):         self.m = m         self.p = p  # iterate on 3 lists "in parallel" using zip(). name, m, p in zip(planet, planetv, planetp):     # create planet , store module-global variable,     # using name 'planet' list.     globals()[name] = planet(m, p) 

now can do:

>>> merc <__main__.planet instance @ 0x...> >>> merc.m 2 >>> merc.p 10 

Comments

Popular posts from this blog

delphi - How to convert bitmaps to video? -

jasper reports - Fixed header in Excel using JasperReports -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -