2012-02-25 743 views
5

我是Python和Django的新手,我從教程中修改了這段代碼。當我加載頁面時,我得到TypeError: count() takes exactly one argument (0 given)。我一直在排除故障和谷歌搜索,似乎無法弄清楚。我究竟做錯了什麼?TypeError:count()只需要一個參數

def report(request): 
    flashcard_list = [] 
    for flashcard in Flashcard.objects.all(): 
     flashcard_dict = {} 
     flashcard_dict['list_object'] = flashcard_list 
     flashcard_dict['words_count'] = flashcard_list.count() 
     flashcard_dict['words_known'] = flashcard_list.filter(known=Yes).count() 
     flashcard_dict['percent_known'] = int(float(flashcard_dict['words_known'])/ flashcard_dict['words_count'] * 100) 
     flashcard_list.append(flashcard_dict) 
    return render_to_response('report.html', { 'flashcard_list': flashcard_list }) 
+1

如果這些答案的幫助,請給予好評,並請接受一個可以幫助你最。 – 2012-02-26 15:53:34

回答

0

您需要提供一些參數給count(x)

It returns the number of times x appears in the list.

>>> mylist = [1,2,3,2] 
>>> mylist.count(2) 
2 
>>> mylist.count() 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: count() takes exactly one argument (0 given) 
>>> 

這是很難理解你想實現你的flashcard_list列表是空的。所以在撥打count之前,您需要在列表中添加一些內容。

10

count需要參數。它返回列表中特定項目的實例數量。

>>> l = range(10) + range(10) 
>>> l.count(5) 
2 

2這裏是5 S IN列表中的號碼。如果你想要一個列表的長度,使用len

>>> len(l) 
20 
0
alist = [] 
alist.append('a') 
alist.count('a') 
1 

這將統計所有的 'a' 在列表中。

2

這是不是很清楚你在這裏試圖做什麼。 flashcard_list是您在循環之前定義的(空)列表。調用Django查詢集函數(如countfilter)是沒有意義的(有一個名爲count的列表方法,但是如錯誤所述,它接受一個參數並計算在列表中找到參數的次數)。

您是不是想要用flashcard.count()代替?這仍然沒有意義,因爲flashcard是單個Flashcard實例,而不是查詢集。你需要更準確地解釋你希望做的事情。評論右後

編輯,所以我認爲這個問題是你要做到這一切在一個循環中,通過每個迭代抽認卡,出於某種原因。事實上,我認爲你根本不需要這個循環。像這樣的東西會更好:

def report(request): 
    flashcard_dict = {} 
    flashcards = Flashcard.objects.all(): 
    flashcard_dict['list_object'] = flashcards 
    flashcard_dict['words_count'] = flashcards.count() 
    flashcard_dict['words_known'] = flashcards.filter(known=True).count() 
    flashcard_dict['percent_known'] = int(float(flashcard_dict['words_known'])/ flashcard_dict['words_count'] * 100) 
    return render_to_response('report.html', flashcard_dict) 

在這裏,你可以看到你在所有卡片的queryset的工作,而不是一個空的列表。而你正在建立一個字典,而不是字典的列表,並且該字典本身成爲模板上下文 - 所以在模板中,你可以參考{{ words_count }}

+0

對不起,我認爲你正在幫助我走上正軌。整個問題的關鍵在於獲取卡片總數以及標記爲「已知」的卡片總數,以便我可以獲得已知總數的百分比。 – Alex 2012-02-25 21:46:27

0

count方法是不是你所期待的對於。在Python列表中,list.count(x)告訴您在list中有多少次出現x。你想要len(flashcard_list)。函數len是一個內置函數,它會告訴你許多Python對象類型的長度。

0

列表的count方法計算的次數,x出現在名單上的量。查看文檔here

如果你想知道在列表中的項目需要使用len()

>>> a = ['a', 'b', 'c'] 
>>> print len(a) 
3 
2

count()發現發生在列表中的項目,因此需要該項目作爲參數的次數的數量。我認爲你在尋找列表中的項目數量。對於這種使用len()count()

flashcard_dict['words_count'] = len(flashcard_list) 
flashcard_dict['words_known'] = len(flashcard_list.filter(known=Yes)) 

count()一個例子是

flashcard_dict['dog_count'] =flashcard_list.count('dog') 
相關問題