Crossin的编程教室

标题: list index out of range [打印本页]

作者: yangyiming    时间: 2017-9-16 21:05
标题: list index out of range
from random import randint

name = input('please inter your name: ')

f = open('game.txt')
lines = f.readline()
f.close()

scores = { } #初始化一个字典
for l in lines:
    s = l.split() #把每一行的数据拆分成list
    scores[s[0]] = strs[1:] #第一项作为key,剩下的作为value IndexError: list index out of range
score = scores.get(name) #查找当前玩家的分数
if score is None:
    score = [0,0,0]      #如果没有这个玩家,则新建一组数据

game_times = int(score[0])
min_times = int(score[1])
total_times = int(score[2])

print(game_times)
print(min_times)
print(total_times)

if game_times>0:
    average_times = float(total_times)/game_times
else:
    average_times = 0

print('%s,you have already played %d times,\
    at least %d times to get the number,\
    at average %.2f times to get the number'%(name,game_times,min_times,average_times))

num = randint(1,50)
print("guess what i think? it's a number between 1 to 50")
bingo = False
times = 0
while bingo == False:
    answer = input()
    answer = int(answer)
    times = times+1
    if answer<num:
        print('too small, guess again')
    if answer>num:
        print('too big, guess again')
    if answer == num:
        print('bingo!')
        bingo = True

if game_times == 0 or times < min_times:
    min_times = times
total_times += times
game_times += 1

scores[name] = [str(game_times), str(min_times), str(total_times)]
result = '' #初始化一个空字符,用来存储数据

#把成绩按照 "name  game_times  min_times  total_games"格式化
for n in scores:
    line = n + ' '+ ' '.join(scores[n])+'\n'
    result += line

f = open('game.txt','w')
f.write(result)
f.close()

这是运行结果

作者: crossin先生    时间: 2017-9-16 23:42
这样看不出来的。你需要去看你的文件内容是否正常
然后再报错之前,把 scores,s,s[0] 这几个值都print出来看是否正常
这是调试代码的基本思路
作者: yangyiming    时间: 2017-9-17 10:17
好的,谢谢!




欢迎光临 Crossin的编程教室 (https://bbs.crossincode.com/) Powered by Discuz! X2.5