[英]How to find number of instances of an item in a python list
I want to part of a script to be something like this. 我希望脚本的一部分是这样的。
if list[1] is in list.pop n times:
return True
Simply use: 只需使用:
list.count(element)
Example: 例:
>>> [1,2,3,4,2,1].count(1)
2
Number of items in a list: 列表中的项目数:
len(myList)
Number of times the i
th element occurs in a list: 第
i
个元素在列表中出现的次数:
myList.count(mylist[i])
Or you can use Counter
: 或者您可以使用
Counter
:
>>> from collections import Counter
>>> Counter([1, 2, 3, 1, 1])
Counter({1: 3, 2: 1, 3: 1})
>>>
This is good if you want to get all the counts of the distinct elements in the list one time. 如果您想一次获取列表中不同元素的所有计数,则这很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.