我正在尝试迭代一个列表,每次在列表中找到一个项目时,它应该增加1.例如:count([1,2,1,1],1)应该返回3(因为1在列表中出现3次。
def count(sequence, item):
sequence = []
found = 0
for i in sequence:
if i in item:
found+=1
return found
答案 0 :(得分:3)
您想测试相等:
if i == item:
found += 1
您使用in
运算符测试包含,但在整数上使用in
会引发异常:
>>> item = 1
>>> 1 in item
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: argument of type 'int' is not iterable
但是,您首先将sequence
反弹到空列表:
sequence = []
因此您的for
循环甚至无法运行,因为没有任何东西可以循环了。工作代码将改为:
def count(sequence, item):
found = 0
for i in sequence:
if i == item:
found += 1
return found
请注意,列表对象有一个专门的方法来计算匹配元素list.count()
:
>>> sequence = [1, 2, 1, 1]
>>> sequence.count(1)
3
答案 1 :(得分:1)
sequence=[]
。你正在覆盖你的参数。
答案 2 :(得分:0)
列表对象已经有一个完全符合你想要的计数方法:
a = [1,1,2,3,4,1,4]
a.count(1) #3
a.count(4) #2
如果您拥有自己的自定义对象集合,请确保在类定义上实现__eq__
方法