2009-12-22 80 views
0
class FriendshipManager(models.Manager):  
     def are_friends(self, user1, user2): 
      if self.filter(from_user=user1, to_user=user2).count() > 0: 
       return True 
      if self.filter(from_user=user2, to_user=user1).count() > 0: 
       return True 
      return False 

,我發現計數() 所以我儘量吧, 但它運行錯誤爲什麼不按我期望的方式在我的代碼中工作count()?

a=[1,2,3,4] 
print a.count() 

a='ssada' 
print a.count() 

爲什麼我的代碼運行錯誤,但FriendshipManager可以運行,謝謝 請儘量使用代碼,而不是文字,因爲我的英文不太好,謝謝

+3

好像人們完全忽略TFM,只是在SO上提出隨機問題。 – 2009-12-22 05:28:27

回答

8

這裏的問題是你混淆了兩個同名的方法。

在Python中的一個序列中,count()的工作原理正好與Dustin描述的「統計序列中參數的出現次數」。

但是,您引用的代碼來自Django模型。在那裏,在過濾器對象上調用count()是SQL分組函數COUNT的別名,它總結了匹配行的數量。

從本質上講,在你的第一個例子和count之後的兩個例子根本不是同一個方法。

+0

+1關於SQL COUNT的部分是一個重要的區別 – 2009-12-22 05:07:41

+0

+1這顯然是正確的答案。 – Omnifarious 2009-12-22 05:21:05

+0

完整性高五! – jathanism 2009-12-22 06:13:42

5

如果您想確定列表的長度/大小,我認爲您想使用len(a)而不是a.count()。無論如何,a.count()實際上需要一個參數。它計算一個值的出現次數。例如:

a = [2, 6, 2, 1, 5, 3, 9, 5] 
print a.count(5) #should display 2 because there are two elements with a value of 5 
print a.count(3) #should display 1 because there is only one element with a value of 3 
3

len對於這種情況是正確的。

>>> a=[1,2,3,4] 
>>> print len(a) 
4 
0

我不確定這是否是正確的答案,但是,試試這個,而不是您擁有的模型管理器代碼。像這樣的課程沒有什麼大的變化。

class FriendshipManager(models.Manager):  
    def are_friends(self, user1, user2): 
     if self.filter(from_user=user1, to_user=user2).count() or self.filter(from_user=user2, to_user=user1).count(): 
      return True 
     return False 

如果count()返回的值不是零,它將始終返回True。

相關問題