一般写法
def count_list(std:list,tongji):
i=0
for item in std:
if item==tongji:
i+=1
print(i)
if __name__=='__main__':
lists=[1,2,3,4,5,1,2,3,4,5,2,2,2,3,4]
count_list(std=lists,tongji=2)
新写法, python 3.5 之后
def count_list(std:list,tongji):
from collections import Counter
name=Counter()
for num in std:
name[num]+=1
print(name[tongji])
if __name__=='__main__':
lists=[1,2,3,4,5,1,2,3,4,5,2,2,2,3,4]
count_list(std=lists,tongji=2)

少了一个if判断,而且 一次可以获取列表所有元素的个数

05-29 00:14