Python Split()索引器
下降的代码给了我想要的结果,但它一直给我相同的错误,程序无法完成Python Split()索引器,python,split,index-error,Python,Split,Index Error,下降的代码给了我想要的结果,但它一直给我相同的错误,程序无法完成 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.spl
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']
2455
['Ines','30,60\n']
3060
['Sofia','18,49\n']
18 49
['Carla','44,64\n']
44 64
['\n']
回溯(最近一次调用last):文件“ex4.1.py”,第13行,在
idade,peso=dados[1]。拆分(“,”)索引器:列表索引超出范围
输入如下:
[Mulheres]安娜=24,55伊内斯=30,60索非亚=18,49卡拉=44,64
[霍姆斯]Joao=20,75 Tiago=55,80 Quim=59,69
你的代码出现空行。您可以使用以下命令跳过所有空行:
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
它会在错误之前打印出
['\n']
,所以这可能是护墙板
,显然在这种情况下护墙板[1]
是一个错误。这意味着行
是'\n'
。