如何创建成员包含数组的数组对象,解决list index out of range报错
报错原因&修正方案
你遇到的list index out of range报错以及运行异常由两个问题导致:
- 语法错误:创建Post实例的行多写了多余的
]符号,属于语法层面的错误 - 逻辑错误:三个
who_reacted_name_postX是独立变量,无法通过循环索引直接匹配到对应的Post实例,当前写法会给所有Post都插入第一组的名单,也不符合你的需求
修改后的完整代码
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_post1 = ['John', 'Marry', 'Franz'] who_reacted_name_post2 = ['Paul', 'Miha', 'Jad'] who_reacted_name_post3 = ['Cody', 'Marvin', 'Will'] # 新增:将三个独立名单按顺序整合为嵌套列表,方便循环索引匹配 all_who_reacted = [who_reacted_name_post1, who_reacted_name_post2, who_reacted_name_post3] for i in range(3): # 修正:删除多余的]符号 post_lists.append(Post(date[i], reactions[i])) # 直接遍历对应索引的名单,插入到当前Post实例中 for name in all_who_reacted[i]: post_lists[i].addName(name)
验证效果
运行后你可以通过如下方式验证结果:
# 输出第二个post的反应者名单,应为['Paul', 'Miha', 'Jad'] print(post_lists[1].who_reacted_name)
内容的提问来源于stack exchange,提问作者Paul Viorel
相关产品推荐
相关产品推荐

