这是一个坏主意。您不应该动态创建变量名称,而应使用字典:
variables = {}
for name, colour, shape in Applist:
variables[name + "_n"] = name
variables[name + "_c"] = colour
variables[name + "_s"] = shape
现在访问它们variables["Apple_n"]
, etc.
不过,你真正想要的可能是一个字典中的字典:
variables = {}
for name, colour, shape in Applist:
variables[name] = {"name": name, "colour": colour, "shape": shape}
print "Apple shape: " + variables["Apple"]["shape"]
或者,也许更好的是,namedtuple:
from collections import namedtuple
variables = {}
Fruit = namedtuple("Fruit", ["name", "colour", "shape"])
for args in Applist:
fruit = Fruit(*args)
variables[fruit.name] = fruit
print "Apple shape: " + variables["Apple"].shape
您无法更改每个变量Fruit
如果你使用namedtuple
虽然(即没有设置variables["Apple"].colour
to "green"
),所以这可能不是一个好的解决方案,具体取决于预期用途。如果你喜欢namedtuple
解决方案但想改变变量,你可以使它成为一个成熟的Fruit
类,它可以用作namedtuple
Fruit
在上面的代码中。
class Fruit(object):
def __init__(self, name, colour, shape):
self.name = name
self.colour = colour
self.shape = shape