为什么它会给我一个无索引错误?当我的所有索引在python中都很好时?

2024-09-25 10:25:48 发布

您现在位置:Python中文网/ 问答频道 /正文

每当我运行它时,输出都是“范围的列表索引put”

我需要将每个字段存储到它们自己的列表中。所以我应该有三个字段,一个表示等级,一个表示权力,还有一个表示这些卡的数量

这是名为“ranks.dat”的文件:

Admiral,30,1 General,25,1 Colonel,20,2 Major,15,2 Captain,10,2 Lieutenant,7,2 Sergeant,5,4 Corporal,3,6 Private,1,10

这是我的密码:

numFile = open("ranks.dat", "r")

rankList = []
skillList = []
powerList = []

while True:
    text = numFile.readline()
    text = text.rstrip("\n")
    if text=="":
        break
    info = text.split(" ")
    rankList.append(info[0])
    skillList.append(int(info[1]))
    powerList.append(int(info[2]))

numFile.close()


print("Admiral\tGeneral\tColonel\tMajor\tCaptain\tLieutenant\tSergeant\tCorporal\tPrivate")

为什么它不起作用


Tags: textinfo列表数量putdatint权力
2条回答

假设您的数据每行有一个条目:

rankList = []
skillList = []
powerList = []

# recommended way to open and close a file
with open("ranks.dat", "r") as file:
    # iterate over every lines in the file
    for line in file.readlines(): 
        # unpack each lines
        rank, skill, power = line.split(',')

        rankList.append(rank)
        skillList.append(skill)
        powerList.append(power)

代码中包含一些错误

首先,它不应该在while循环中,而是(如果有的话)在for line in text

其次,当您split(" ")时,您会得到一个列表,其中的每个项都包含"RANK,SKILL,POWER"形式的字符串。您应该将其拆分为每个逗号,然后将项目附加到列表中

最后,我强烈建议检查输入的有效性(比如检查分割的info中是否有三项)

诸如此类:

rankList = []
skillList = []
powerList = []

fil = open("ranks.dat", "r")
data = fil.read()
fil.close()

for item in data.split():
      info = item.split(',')
      if len(info) != 3:
            continue
      rankList.append(info[0])
      skillList.append(int(info[1]))
      powerList.append(int(info[2]))

# and do whatever you want

这取决于文件的来源,但完整正确的代码将首先检查文件是否存在,以及等级、技能和权限的值是否有效

相关问题 更多 >