8

私はPythonで遊んでいて、解決する必要があるこのリストがあります。基本的に、ゲームのリストを多次元配列に入力すると、それぞれのゲームについて、最初のエントリに基づいて 3 つの変数が作成されます。

作成される配列:

Applist = [
['Apple', 'red', 'circle'],
['Banana', 'yellow', 'abnormal'],
['Pear', 'green', 'abnormal']
]

各果物に名前、色、形を割り当てる for ループ。

for i in Applist:
    i[0] + "_n" = i[0]
    i[0] + "_c" = i[1]
    i[0] + "_s" = i[2]

ただし、これを行うと、オペレーターに割り当てることができないというメッセージが表示されます。どうすればこれに対抗できますか?

期待される結果は次のようになります。

Apple_n == "Apple"
Apple_c == "red"
Apple_s == "circle"

などなど、各フルーツに。

4

2 に答える 2

23

これは悪い考えです。変数名を動的に作成するのではなく、代わりに辞書を使用してください。

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
于 2012-06-20T11:31:01.350 に答える
2

辞書を使用してこれを行うのが最も簡単です。

app_list = [
    ['Apple', 'red', 'circle'],
    ['Banana', 'yellow', 'abnormal'],
    ['Pear', 'green', 'abnormal']
]
app_keys = {}

for sub_list in app_list:
    app_keys["%s_n" % sub_list[0]] = sub_list[0]
    app_keys["%s_c" % sub_list[0]] = sub_list[1]
    app_keys["%s_s" % sub_list[0]] = sub_list[2]
于 2012-06-20T11:32:17.433 に答える