2015-07-13 58 views
1

這裏我想創建一個List(score []),我可以在其中添加,刪除,顯示和排序分數值。那麼排序時,我得到一個錯誤,這是代碼之後提到:實現列表並嘗試Python中的幾種方法

score=[]; 
choice=None; 
while choice!=0: 
print "1. Dislplay the score\n"; 
print "2. Add the score\n"; 
print "3. Delete a score\n"; 
print "4. Sort the scores\n"; 
choice=raw_input("enter the choice\n"); 
if choice=="1": 
    print score; 
elif choice=="2": 
    print "enter the no. of scores u want to update"; 
    add=int(raw_input("enter the scores u know:\n")); 
    i=0; 
    while i<add: 
     scores=int(raw_input("enter the score\n")); 
     score.append(scores); 
     i+=1; 
elif choice=="3": 
    print "enter the score you want to delete or remove:\n"; 
    del_score=int(raw_input("delete score:\n")); 
    if del_score in score: 
     score.remove(del_score); 
    else: 
     print "the required score is not found in the list"; 
elif choice=="4": 
    print "now its time to sort the scores in list\n"; 
    sorted_score=score.sort(); 
    sorted_sore=sorted_score.reverse(); 
    print sorted_score; 
else: 
    print "you have entered a wrong choice mate "; 

的錯誤是 -

Error :Traceback (most recent call last): 
    File "C:\Users\Shijith\Desktop\python exer\listmethodsscore.py", line 29, in <module> 
    sorted_score=sorted_score.reverse(); 
AttributeError: 'NoneType' object has no attribute 'reverse' 
+1

網站注:在結束所有這些分號可省略。 –

回答

1

通過Python docs

sort() and reverse()方法在排序或反轉大型列表時,修改列表以實現空間節約。爲了提醒您,他們以副作用的方式操作,他們不會返回排序或顛倒的列表。

因此,.sort().reverse()改變了給定的列表,所以不返回任何值。與此

score.sort(reverse=True) 

sorted_score=score.sort() 
sorted_sore=sorted_score.reverse() 

得到它的工作:您應該替換以下。

另外,如果你希望你的score動那個列表,你應該使用sorted()超過sort()這將創造一個新的列表,並保持現有的原樣。

reversed_scores = sorted(score, reverse=True) 

以下是關於如何在Python中進行排序的很好的article

+0

呵呵,謝謝mate @ozgur它工作正常:))) – SJith

1

您正在嘗試第一個排序和扭轉sorted_sore列表 但你將sorted.sort()的結果存儲在sorted_score中,這是沒有意義的,因爲.sort()方法就位,所以只有做score.sort()就足夠了。

另外如果你想扭轉它既可以使用反轉()方法或如[:: - 1] 反向切斷方法

PS:也.reverse()方法是就地所以將其分配給變量犯規有道理

+1

感謝它的工作! :)並感謝通過切片反轉列表的想法! – SJith

+0

@Sjith再次標記正確的答案和歡呼聲! – therealprashant

1

score.sort()不返回任何東西。它只是對數組進行排序而不返回它。所以,你的排序應該是:

score.sort(); 
score.reverse(); 
print score; 

所以,最簡單的方式去了解它是當sort()方法被調用時,反向陣列分配給score變量,而不是返回。

0

由於sort()是一種對列表進行排序的方法,它不會返回任何內容。所以,如果你在Python解釋器寫:

a = [1,2,3] 
b = a.sort() 
b is None 

您將獲得:

True 

做a.sort()後, 'A' 進行排序。

在您的例子:

sorted_score=score.sort(); 
sorted_sore=sorted_score.reverse(); 

實際情況是,「sorted_score」成爲無,然後你嘗試過類似None.reverse(),它產生的錯誤。

0

列表的.sort()方法對列表進行排序,而sorted()創建一個新列表。

所以

sorted_score = score.sort(); 

分配無給變量。

因此,當你扭轉它

sorted_sore = sorted_score.reverse() 

你得到一個錯誤,正確。

BTW你有一個錯字那裏(sorted_sore)以及不必要的分號遍佈代碼

相關問題