[英]Counting elements of a list in Python
I am trying to define a function that takes two inputs, a list and an item (could be a string, int, float) and it returns the number of times the item appears in a list. 我试图定义一个函数,它接受两个输入,一个列表和一个项目(可以是一个字符串,int,浮点数),它返回项目在列表中出现的次数。 Here's my code:
这是我的代码:
def count(sequence,item):
for all x in sequence:
if x != item:
while x in sequence:
sequence.remove(x)
return len(sequence)
however, this only deletes the first element not equal to the item in the sequence and deletes it. 但是,这只会删除不等于序列中项目的第一个元素并删除它。 For example, count([4,8,3],3) returns 2, for it only deletes 4 from the list.
例如,count([4,8,3],3)返回2,因为它只从列表中删除4。 I thought the for loop was supposed to take care of that.
我认为for循环应该照顾它。
Any suggestions? 有什么建议么?
It's as simple as this, using the count
method: 这很简单,使用
count
方法:
the_list.count(the_item)
From the documentation: 从文档:
list.count(x)
Return the number of times x appears in the list.list.count(x)
返回x在列表中出现的次数。
For example: 例如:
[1, 2, 3, 1, 4].count(1)
=> 2
And by the way - I don't get it, why are you deleting elements in a function that's supposed to simply count them? 顺便说一句 - 我不明白,为什么要删除一个应该简单计算它们的函数中的元素?
It is dangerous when you iterate a list and change the length of this list (you use remove()) 迭代列表并更改此列表的长度(使用remove())是危险的
In your case, When you are iterating the list 'sequence', at first you will get sequence[0] (that is 4). 在您的情况下,当您迭代列表'序列'时,首先您将获得序列[0](即4)。 And you remove it.
你删除它。 Then, you will get sequence[1].
然后,你将得到序列[1]。 You suppose sequence[1] is 8. However, because you remove 4 before, now sequence[0] is 8 and sequence[1] is 3. So what you get is not 8 but 3. That is why you can't remove 8 from sequence.
你假设序列[1]是8.但是,因为你之前删除了4,现在序列[0]是8而序列[1]是3.所以你得到的不是8但是3.这就是为什么你不能删除8从序列。 You ignore it.
你忽略它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.