这是一个坏主意。您不应该动态创建变量名称,而是使用字典:
variables = {}
for name, colour, shape in Applist:
variables[name + "_n"] = name
variables[name + "_c"] = colour
variables[name + "_s"] = shape
现在以variables["Apple_n"]
等方式访问它们。
不过,您真正想要的也许是 dicts 的 dict:
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
为),则无法更改每个变量的变量"green"
,因此根据预期用途,它可能不是一个好的解决方案。如果您喜欢该namedtuple
解决方案但想更改变量,则可以将其改为一个成熟的Fruit
类,它可以用作namedtuple
Fruit
上述代码中的替代品。
class Fruit(object):
def __init__(self, name, colour, shape):
self.name = name
self.colour = colour
self.shape = shape