2014-12-13 46 views
1

對不起,如果我得到這個錯誤,這是我的第一篇文章。Python - 不能在列表中添加1個以上的分數

我寫了一個程序,以保持板球運動員列表和他們的分數,並添加新的分數,他們的理貨工作正常,但是當我添加一個新的擊球手時,我不能添加超過一個分數。任何人都可以看到我做錯了,請我現在已經在這裏兩天了。下面是代碼: -

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 
+0

你的意思是「我不能添加多個分數」是什麼意思? – martineau 2014-12-13 15:08:10

+0

請添加一些示例輸入並顯示其輸出。您的問題非常混淆 – 2014-12-13 15:08:23

+0

對不起,如果我選擇選項2並添加名稱Bert並給他一個分數,它將它保存到列表中,但是如果我然後嘗試爲Bert添加另一個分數,它將不起作用 – 2014-12-13 15:12:53

回答

0

替換:

arr = (name,score) 

有:

arr = [name,score] 

事情是你使用的是tuple當添加一個新的球員。但tuples不可變的在Python中,你不能修改它們。這就是你無法向新玩家追加更多分數的原因。用list代替tuple將解決問題,因爲lists可變

+0

真是太棒了,真心地謝謝你,我一直在努力工作 – 2014-12-13 15:21:27

+0

Y're welcome ... – 2014-12-13 15:24:00

+0

如果你認爲它有幫助,你可以接受答案... – 2014-12-13 15:34:07