Python 列表作为变量名

标签 python arrays list variables multidimensional-array

<分区>

我一直在玩 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

关于Python 列表作为变量名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11118486/

相关文章:

Java (6) 哈希和数组替代品,其行为更像 Ruby 对应物

PHP 获取给定目录的所有子目录

python asyncore 在客户端连接后使用 100% CPU

python - 从数据框中的日志创建同现表

javascript - 根据数组对数组对象进行排序

c - 为什么 C 数组在传递大小时衰减为指针

r - 在 data.frames 列表中合并 n 个列表

c# - 如何允许用户更改列表框顺序

python - 如何将表中特定列的每一行的长度与支持表中的特定值相对应,并在满足条件时创建标志?

python - 使用 Kivy 如何在 ScrollView 中生成缩放按钮