我一直在玩 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]
不过,在执行此操作时,我收到无法分配给运算符(operator)的消息。我该如何应对?
预期的结果是:
Apple_n == "Apple"
Apple_c == "red"
Apple_s == "circle"
每个水果等等。
这是个坏主意。你不应该动态创建变量名,而是使用字典:
variables = {}
for name, colour, shape in Applist:
variables[name + "_n"] = name
variables[name + "_c"] = colour
variables[name + "_s"] = shape
现在以变量["Apple_n"]
等方式访问它们
不过,您真正想要的可能是一个 dict of dicts:
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
如果您使用 namedtuple
,则不能更改每个 Fruit
的变量(即没有设置 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