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.
Array that is made:
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?
The expected result would be:
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:
Now access them as
variables["Apple_n"], etc.What you really want though, is perhaps a dict of dicts:
Or, perhaps even better, a
namedtuple:You can’t change the variables of each
Fruitif you use anamedtuplethough (i.e. no settingvariables["Apple"].colourto"green"), so it is perhaps not a good solution, depending on the intended usage. If you like thenamedtuplesolution but want to change the variables, you can make it a full-blownFruitclass instead, which can be used as a drop-in replacement for thenamedtupleFruitin the above code.