Python - 无法在列表中添加超过1的分数

时间:2014-12-13 15:02:41

标签: python list append

对不起,如果我弄错了,这是我的第一篇文章。

我写了一个程序来保持板球运动员和他们的分数的列表,并在他们的计数中添加新的分数,但是当我添加新的击球手时,我不能添加多个分数。任何人都可以看到我做错了什么,我现在已经在这两天了。这是代码: -

import pickle
scores = [["Moe", 100], ["Curly", 50], ["Larry", 0]]

#setup the save function same as usual
def save_scores():
    file = open("pickle.dat", "wb")
    pickle.dump(scores, file)
    file.close()
    print('Scores Saved')
    print()

#setup the load same as yours    
def load_scores():
    file = open("pickle.dat", "rb")
    scores = pickle.load(file)
    file.close()
    print(scores)
    print()

#print the scores to the screen
def print_scores():
    for i in range(0,len(scores)):
        print(scores[i])
    print()

#add a score to the list        
def add_score():
    #first setup a flag like in a bubble sort. This will show if we find a name
    flag = False
    a = ''
    #ask for the name and the new score
    name = input("Enter your name: ")
    score = int(input("Enter your score: "))
    #now count through the list of names
    for i in range (0,len(scores)):
        #take out each name and store it in var a
        a = (scores[i][0])
        #strip the space off the end. Unfortunately, when Python stores names
        #in a list it adds spaces to the end of them. The only way to strip them
        #off is to put them in a variable first, hence a
        a.replace(' ','')
        #now we set the flag if we find the name we just typed in
        if a == name:
            #and add the score to the name in the list
            scores[i].append(score)
            flag = True
    #if we get to here and the flag is still false then the name doesn't exist
    #in the list so we add the name and the score to the list
    if flag == False:
        arr = (name,score)
        scores.append(arr)

def print_menu():
    print('1. Print Scores')
    print('2. Add a Score')
    print('3. Load Scores')
    print('4. Save Scores')
    print('5. Quit')
    print()

menu_choice = 0
print_menu()
while True:
    menu_choice = int(input("Type in a number (1-5): "))
    if menu_choice == 1:
        print_scores()
    if menu_choice == 2:
        add_score()
    if menu_choice == 3:
        print_scores()
    if menu_choice == 4:
        save_scores()
    if menu_choice == 5:
        print ("Goodbye")
        break

1 个答案:

答案 0 :(得分:0)

替换:

arr = (name,score)

with:

arr = [name,score]

当添加新玩家时,你正在使用tuple。但是tuples 不可变在python中你无法修改它们。这就是你无法向新玩家追加分数的原因。将tuple替换为list将解决问题,因为lists 可变