Python List as variable name

后端 未结 2 1346
花落未央
花落未央 2020-12-28 11:03

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 m

2条回答
  •  不知归路
    2020-12-28 11:40

    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
    

    Now access them as variables["Apple_n"], etc.

    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"]
    

    Or, perhaps even better, 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
    

    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
    

提交回复
热议问题