似乎无法弄清楚为什么这不起作用。 python初学者

时间:2014-06-18 13:19:50

标签: python python-2.7

我正在尝试迭代一个列表,每次在列表中找到一个项目时,它应该增加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 

3 个答案:

答案 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)

Martijn Pieters&#39;回答加上删除行sequence=[]。你正在覆盖你的参数。

答案 2 :(得分:0)

列表对象已经有一个完全符合你想要的计数方法:

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

如果您拥有自己的自定义对象集合,请确保在类定义上实现__eq__方法