Home > Software design >  How to create an array object that has array as member? [closed]
How to create an array object that has array as member? [closed]

Time:09-17

I used the following code but it doesn't work. I got list index out of range error.

class Post:
    def __init__(self, date, reactions):
        self.date = date
        self.reactions = reactions
        self.who_reacted_name = []
    def addName(self, namex):
        self.who_reacted_name.append(namex)

Below are my variables that I want to insert them into the post_list array object. But my struggle is that I do not know how to add who_reacted_name_post1, who_reacted_name_post2 & who_reacted_name_post3 into the post_list array.

post_lists = []

date = ['2021', '2020', '2019']
reactions = ['99', '77', '34']
who_reacted_name_post1 = ['John', 'Marry', 'Franz']
who_reacted_name_post2 = ['Paul', 'Miha', 'Jad']
who_reacted_name_post3 = ['Cody', 'Marvin', 'Will']

for i in range(3):
    post_lists.append(Post(date[i],reactions[i]]))
    
    for j in range (3):
        post_lists[i].addName(who_reacted_name_post1[j]) #doesn't work
```

CodePudding user response:

From what I understood from your question, I hope this solution works.
I included all the individual instances of who_reacted_nameX into a nested list so it could be accessed easier.

class Post:
    def __init__(self, date, reactions):
        self.date = date
        self.reactions = reactions
        self.who_reacted_name = []
    def addName(self, namex):
        self.who_reacted_name.append(namex)

post_lists = []

date = ['2021', '2020', '2019']
reactions = ['99', '77', '34']
who_reacted_name_post = [['John', 'Marry', 'Franz'] , ['Paul', 'Miha', 'Jad'] , ['Cody', 'Marvin', 'Will']]

for i in range(3):
    post_lists.append(Post(date[i],reactions[i]))
    
for j in range (3):
    obj = post_lists[j]
    obj.addName(who_reacted_name_post[j])

for i in range(0, 3):
    obj = post_lists[i]
    print(obj.date, obj.reactions, obj.who_reacted_name)

Output

2021 99 [['John', 'Marry', 'Franz']]
2020 77 [['Paul', 'Miha', 'Jad']]
2019 34 [['Cody', 'Marvin', 'Will']]
  • Related