设为首页收藏本站

Crossin的编程教室

 找回密码
 立即加入
楼主: mty1111
打印 上一主题 下一主题

【Python 第41课】 用文件保存游戏(3)

[复制链接]

0

主题

0

好友

8

积分

新手上路

Rank: 1

楼主
发表于 2018-11-8 21:00:24 |显示全部楼层
from random import randint

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


scores = {}
for i in lines:
    a = i.split()
    scores[a[0]] = a[1:]
   
name  = input('请输入你的名字:')
运行后报错
Traceback (most recent call last):
  File "C:\Users\xiao hua\AppData\Local\Programs\Python\Python37\测试2.py", line 11, in <module>
    scores[a[0]] = a[1:]
IndexError: list index out of range
求解这个是什么问题,非常感谢!
回复

使用道具 举报

0

主题

0

好友

8

积分

新手上路

Rank: 1

沙发
发表于 2018-11-9 15:17:34 |显示全部楼层
本帖最后由 吃土小华 于 2018-11-9 15:18 编辑
吃土小华 发表于 2018-11-8 21:00
from random import randint

f = open('game.txt')

之前的问题已经解决了,可能是因为文本后面空白行的原因。
新的问题是这个
from random import randint

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


scores = {}
for l in lines:
   s = l.split()

   scores[s[0]] = s[1:]

   
name  = input('请输入你的名字:')
score = scores.get(name)
if score is None:
    score = [0,0,0]

game_time = int(score[0])
min_time = int(score[1])
total_time = int(score[2])
if game_time>0:
    avg_times = float(total_time)/game_time
else:
    avg_times = 0

print('%s,你已经玩了%d次,最少%d轮猜出答案,平均%.2f轮猜出答案。'%(name,game_time,min_time,avg_times))

num = randint(1,100)
time=0
bingo= False
print('Guess what I think.')
while bingo==False:
    answer=int(input())
    time+=1
    if answer<num:
        print('too small')
    if answer>num:
        print('too big')
    if answer==num:
        print('bingo')
        bingo=True

total_time +=time
if game_time==0 or time<min_time:
    min_time=time
game_time+=1
print(game_time,min_time,total_time)
game_times=str(game_time)
mins=str(min_time)
total=str(total_time)
scores[name] = {game_times,mins,total}
print(scores[name])
result=''
for n in scores:
    line = n +' '+' '.join(scores[n])+'\n'#line为字符串
    result += line


#f=open('game.txt','w')
#f.write(result)
#f.close()
这样写完后显示
请输入你的名字:小华
小华,你已经玩了0次,最少0轮猜出答案,平均0.00轮猜出答案。
Guess what I think.
50
too big
60
too big
25
too small
35
too small
40
too small
45
too small
48
too small
49
bingo
1 8 8
{'1', '8'}
>>>
其中小华的所有数值无法写入到字典里,只能显示两个值,文本文档中的内容和公众号一致,非常疑惑这是为什么,求大神解答,非常感谢。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即加入

QQ|手机版|Archiver|Crossin的编程教室 ( 苏ICP备15063769号  

GMT+8, 2024-5-3 13:07 , Processed in 0.024930 second(s), 22 queries .

Powered by Discuz! X2.5

© 2001-2012 Comsenz Inc.

回顶部