为什么count()在我的代码中没有按照我期望的方式工作?

zjm*_*126 0 python django

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
Run Code Online (Sandbox Code Playgroud)

我发现count()所以我尝试了,但它运行错误

a=[1,2,3,4]
print a.count()
Run Code Online (Sandbox Code Playgroud)

要么

a='ssada'
print a.count()
Run Code Online (Sandbox Code Playgroud)

为什么我的代码运行错误,但是FriendshipManager可以运行,谢谢请尽量使用代码,而不是文本,因为我的英文不是很好,谢谢

Tra*_*haw 8

这里的问题是你混淆了两个同名的方法.

在Python中的序列中,count()Dustin描述的工作正是"计算序列中参数出现次数".

但是,您引用的代码来自Django模型.在那里,调用count()filter对象是SQL分组函数的别名COUNT,它总结了匹配行的数量.

实质上,count在您的初始示例和count之后的两个示例中根本不是相同的方法.


Dus*_*tin 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
Run Code Online (Sandbox Code Playgroud)