Reputation: 164
I want to create a list of items where each item may have more than one variable. I read about dict, but there its just two variables. Then I thought of class. However I am not sure how to implement class object inside a list. I would also like to store the data in a db. Can you give me an explanation of how to implement this logic in the code?
Upvotes: 0
Views: 487
Reputation: 263
There are a few ways you can do this. I'll go from easy to harder.
A multi-dimensional array is like an array inside an array, like this:
If we wanted to store pets with their animal type and age
CODE:
multi-array = [["dog", 8], ["cat", 10]]
DanielsPet = multi-array[0]
print(DanielsPet[1])
RESULT:
8
Now although this works you have to try and remember a numerical value for everything (you could of course have 'age = 1' and sub that into DanielsPet[age])
Now it sounds like you haven't looked into classes very much so I am going to be brief with this one, let me know if you want more information.
Steps:
read / edit the instances
#basic class
class basic:
def __init__(self, x, y):
self.x = x
self.y = y
list = [basic(5, 10), basic(10, 20)]
print (list[0].x, list[1].y)
list[0].x = 15
print (list[0].x, list[1].y)
RESULT:
(5, 20)
(15, 20)
Here we are able to store 'instances' of a class which all contain their own variables, these can easily be changed and reprinted (list[0].x = 15)
Let me know if you need anymore help or want a more specific example.
Upvotes: 1