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

2024-10-04 09:30:06 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我找到了伯爵() 所以我试试看, 但它错了

^{pr2}$

或者

a='ssada'
print a.count()

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


Tags: tofromselftruereturnifmodelscount
3条回答

如果要确定列表的长度/大小,我想您应该使用len(a),而不是{}。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

莱恩是那个案子的正确人选。在

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

这里的问题是您混淆了两个同名的方法。在

{account在cython>序列中的出现次数正好描述了在cd1>中出现的次数

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

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

相关问题 更多 >