操作列表以提高代码效率,挣扎

时间:2012-03-07 15:16:12

标签: python vpython

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]

基本上,我想创建如下的新变量:

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

...

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

...

不更改planet列表,因为我需要在代码后面访问' merc',' venus'等。

4 个答案:

答案 0 :(得分:4)

如果我理解正确,您希望使用列表planet给出的名称创建全局变量,每个变量绑定到具有属性mp的对象,分别设置为列表planetvplanetp中的值。

如果这是正确的,可以采用以下方法:

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

现在你可以做到:

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

答案 1 :(得分:2)

嗯,行星只是字符串,所以你不能在它们上设置属性。此外,动态创建大量全局变量,正如Ferdinand所暗示的那样非常非常很少是一个好主意,最好使用dict

在费迪南德回答的基础上,我建议将行星的名称作为属性包括在内(我想你会发现你需要它)。现在,您可以在Planetdict中保留这些list个对象(以保留订单),无论您当时的需求是什么,所有相关信息都可以随时提供两种情况。

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]

class Planet(object):
    def __init__(self, name, m, p):
        self.name = name
        self.m = m
        self.p = p

planets = [Planet(name, m, p) for name, m, p in zip(planet, planetv, planetp)]
planet_dict = dict((p.name, p) for p in planets)

for p in planets:
    print "{0}: {1} {2}".format(p.name, p.m, p.p)
print "Mass of earth: {0}".format(planet_dict["earth"].m)

编辑:忘掉我以前的建议,我改变了主意。

答案 2 :(得分:0)

为了简单起见,我会使用字典来创建映射。

喜欢这个 -

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]

planet_map = {}

for i, p in enumerate(planet):
    planet_map[p] = {'m': planetv[i],
                     'p': planetp[i],
                    }

print planet_map

现在,您可以访问planet_map['merc']['m']planet_map['merc']['p']

答案 3 :(得分:0)

你有想过用字典做这个吗?

planetv_dic = {'merc':2, 'venus': 3,'earth':4,'mars': 5,'jupiter': 6,'saturn': 7,'uranus': 8,'neptune': 9}

planetp_dic = {'merc':10, 'venus': 20,'earth':30,'mars': 40,'jupiter': 50,'saturn': 60,'uranus': 70,'neptune': 80}

或者假设您已经有了列表,请使用for循环构建词典:

 planetv_dic = {}
 planetp_dic = {}
 for i in xrange(len(planet)):
    planetv_dic[planet[i]] = planetv[i]
    planetp_dic[planet[i]] = planetp[i]
然后,您可以使用

之类的内容访问您的行星列表
 planetv_dic.keys()
相关问题