好吧,从技术上讲,我被分配了一项任务来完成,它涉及循环(while、for 等),我遇到了一个问题:
我被要求以这样的列表格式存储分数和用户名、级别等:
# <username>, <level>, <level_score> - Like this:
['buzzysin,5,100','apple_maple,3,60','choco_charlie,2,25','buzzysin,1,10']
我需要做的是使用这些数据创建一个记分牌,但我似乎无法将分数与列表中的字符串隔离开来。这是我的代码片段:
def scoreboard():
name = input("Enter a username: ") # Say 'buzzysin'
t = open('scores.txt', 'r')
a = t.readlines()
b = []
t.close()
for i in range(len(a)):
if name not in a[i]:
pass
else: # Here I need to get the occurences of 'buzzysin' and append it to b
b.append(a[i])
#Then I need to extract the level and scores, but here's where I'm stuck :-(
我的记分牌需要如下所示:
>>> scoreboard()
Please enter a name: buzzysin
The scores for buzzysin are:
Level Scores
-----------------------
1 10
2 0
3 0
4 0
5 100
>>>
请帮忙,
'buzzysin'
请您参考如下方法:
首先,for i in len(a) 会引发异常,因为整数是不可迭代的。您应该直接迭代 a 或迭代索引列表,如 range(len(a))。其次,如果 a 中的行格式如下 buzzysin,5,100 你应该使用 in 的 string.startswith intead >(节省了大量时间)。然后,如果字符串以 buzzysin 开头,您可以使用 string.split(',') 解析该字符串以获得分数。例如,
for line in a:
if line.startswith(player_name):
name, level, score = line.rstrip().split(',')
