Python Split()IndexError

代码下降给了我想要的结果,但是它却不断给我同样的错误,并且程序没有完成。

totalIdadesM = 0
totalIdadesH = 0

countM = 0
countH = 0

with open("info.txt","r") as infoFile:
    for line in infoFile:
        if line[1] == "M":
            for line in infoFile:
                dados = line.split("=")
                print(dados)
                idade,peso = dados[1].split(",")

                print(idade)
                print(peso)


                if idade.isdigit():
                    totalIdadesM += int(idade)
                    countM += 1

        print(countM)
def calcMedia(total,num):
    media = total / num
    return media

那是错误

  

['Ana','24,55 \ n']

     

24 55

     

['Ines','30,60 \ n']

     

30 60

     

['Sofia','18,49 \ n']

     

18 49

     

['Carla','44,64 \ n']

     

44 64

     

['\ n']

     

回溯(最近一次通话最后一次):文件“ ex4.1.py”,第13行,在          idade,peso = dados [1] .split(“,”)IndexError:列表索引超出范围

输入如下:

  

[Mulheres] Ana = 24,55 Ines = 30,60 Sofia = 18,49 Carla = 44,64

     

[Homens] Joao = 20,75 Tiago = 55,80 Quim = 59,69

vistbo 回答:Python Split()IndexError

您的代码空了一行。您可以这样跳过所有空行:

for line in infoFile:
    line = line.strip()
    if not line: # empty line
        continue # skip the body and go staring to next iteration

    dados = line.split("=")
    ...

我不确定的一件事就是为什么要遍历infoFile 两次。当您进行迭代时,您正在从中读取内容,例如,在这里,第一行将被跳过:

for line in infoFile:
    # read first line
    if line[1] == "M":
        for line in infoFile:
            # first line has already been read,so read the second line,# thus skipping the first one altogether
            ...
        # the loop will be exited when there'll be no more data to read
    # so the outer loop will terminate since there's nothing to iterate over anymore
本文链接:https://www.f2er.com/2975001.html

大家都在问