每当我运行它时,输出都是“范围的列表索引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")
为什么它不起作用
假设您的数据每行有一个条目:
代码中包含一些错误
首先,它不应该在
while
循环中,而是(如果有的话)在for line in text
中其次,当您
split(" ")
时,您会得到一个列表,其中的每个项都包含"RANK,SKILL,POWER"
形式的字符串。您应该将其拆分为每个逗号,然后将项目附加到列表中最后,我强烈建议检查输入的有效性(比如检查分割的
info
中是否有三项)诸如此类:
这取决于文件的来源,但完整正确的代码将首先检查文件是否存在,以及等级、技能和权限的值是否有效
相关问题 更多 >
编程相关推荐