これは悪い考えです。変数名を動的に作成するのではなく、代わりに辞書を使用してください。
variables = {}
for name, colour, shape in Applist:
variables[name + "_n"] = name
variables[name + "_c"] = colour
variables[name + "_s"] = shape
variables["Apple_n"]
などとしてアクセスします。
あなたが本当に欲しいのは、おそらく辞書の辞書です:
variables = {}
for name, colour, shape in Applist:
variables[name] = {"name": name, "colour": colour, "shape": shape}
print "Apple shape: " + variables["Apple"]["shape"]
または、おそらくさらに良いのは、 a 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