python中line.split_Python line.split只作用于一行(Python line.split only acts on one line)

I have a list of highscores (saved in a text file as the score, space, name (no commas)). However, when I go to retrieve the data, it appears only the first line is read.

for line in previous_scores:

data = line.split()

current_data = data[0]

if int(current_data) > highscore:

highscore = current_data

highscore_names = [data[1]]

elif int(current_data) == highscore:

highscore_names.append(data[1])

For example, with the data below:

2 James

3 Anna

5 Emily

It would return the highscore as James, with his score being 2.

If my code is wrong could you please tell me what is wrong, and if your really awesome fix it. I don't mind if there is a better way to do this.

Edit:

The file is opened with:

previous_scores = open("Scores.txt", "a+")

Edit 2:

I added some extra lines on the end, and updated the code for testing to the following:

for line in previous_scores:

data = line.split()

current_data = data[0]

print "1 " + data[0]

print "2 " + current_data

if int(current_data) > highscore:

print "3 " + current_data

highscore = current_data

highscore_names = [data[1]]

elif int(current_data) == highscore:

print "4 " + current_data

highscore_names.append(data[1])

elif int(current_data) < highscore:

print "5 " + current_data

The first score always returns 1, 2 and 3, and then all other scores return 1, 2 and 5.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值