Python列表变量名 [英] Python List as variable name

查看:245
本文介绍了Python列表变量名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在玩Python和我有这个名单,我需要制定。基本上我的游戏类型列表到多维数组,然后每个人,它会基于第一个条目使3个变量。

I've been playing with Python and I have this list that I need worked out. Basically I type a list of games into the multidimensional array and then for each one, it will make 3 variables based on that first entry.

阵列即发:

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

有关循环,每个水果指定名称,颜色和形状。

For loop to assign each fruit a name, colour and shape.

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

在这样做,虽然,我得到一个不能分配给操作员消息。我该如何应对呢?

When doing this though, I get a cannot assign to operator message. How do I combat this?

预期的结果将是:

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

等,为每个水果。

Etc for each fruit.

推荐答案

这是一个坏主意。你不应该动态地创建变量名,使用字典来代替:

This is a bad idea. You should not dynamically create variable names, use a dictionary instead:

variables = {}
for name, colour, shape in Applist:
    variables[name + "_n"] = name
    variables[name + "_c"] = colour
    variables[name + "_s"] = shape

现在访问它们为变量[Apple_n]

你真正想要什么,虽然,也许是类型的字典的字典:

What you really want though, is perhaps a dict of dicts:

variables = {}
for name, colour, shape in Applist:
    variables[name] = {"name": name, "colour": colour, "shape": shape}

print "Apple shape: " + variables["Apple"]["shape"]

或者,也许甚至更好,一<一href=\"http://docs.python.org/library/collections.html#collections.namedtuple\"><$c$c>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 虽然(即没有设置变量[苹果。颜色绿色),所以它也许不是一个好的解决方案,这取决于预期的用法。如果你喜欢 namedtuple 解决方案,但想改变的变量,你可以把它一个完全成熟的水果类,而不是,它可以用作上述code一个下拉更换为 namedtuple 水果

You can't change the variables of each Fruit if you use a namedtuple though (i.e. no setting variables["Apple"].colour to "green"), so it is perhaps not a good solution, depending on the intended usage. If you like the namedtuple solution but want to change the variables, you can make it a full-blown Fruit class instead, which can be used as a drop-in replacement for the namedtuple Fruit in the above code.

class Fruit(object):
    def __init__(self, name, colour, shape):
        self.name = name
        self.colour = colour
        self.shape = shape

这篇关于Python列表变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆