Python类类型错误'没有属性__getitem___

时间:2014-12-01 07:04:03

标签: python class types

我写了以下课程:

class Average(object):

def __init__(self,invoer):
    self.regel = invoer
    self.persons = []

def parse_input(self):        
    lengte = self.regel.split('\t')[2]
    gewicht = self.regel.split('\t')[3]
    self.lengte = float(lengte)
    self.gewicht = float(gewicht)
    return self.lengte, self.gewicht

def add_person(self):
    self.persons += [self.lengte, self.gewicht]

def get_average_bmi(self):
    total_bmi = 0
    for i in self.persons:
        total_bmi += i[0]/i[1]
    average_bmi = total_bmi/len(self.persons)
    self.average = average_bmi
    return self.average

该计划如下:

from BodyMassIndex import Average 
from ipy_lib import file_input

bestand = file_input().splitlines()

for i in bestand:
    bmi = Average(i)
    bmi.parse_input()
    bmi.add_person()
average_bmi = bmi.get_average_bmi()

最佳变量中的输入如下所示:

Barbara Lerner  V   1.54    67  No
Danny Coronado  M   1.84    89  No
Diana Knox  V   1.69    58  Yes
Penney Rose V   1.56    102 No
Jessica Richman V   1.58    63  Yes

parse_input()方法获取每个人的长度,add_person将其添加到列表中,get_average_bmi应该计算该列表中每个列表的bmi并计算其平均值。

然而,我收到此错误:     total_bmi + = i [0] / i [1]     TypeError:'float'对象没有属性' getitem '

此代码出了什么问题?

1 个答案:

答案 0 :(得分:0)

您需要修复add_person()

def add_person(self):
    self.persons.append([self.lengte, self.gewicht])