品易云推流 关闭
文章详情页
文章 > Python基础教程 > Python count()方法怎么用?怎么计数?

Python count()方法怎么用?怎么计数?

头像

2020-11-05 15:19:5815746浏览 · 0收藏 · 0评论

本期又给大家带来了python的函数,与之前不一样的是,这个是可以计算的哦~想要了解的小伙伴一起来看下吧~

Python列表计数count()方法

count()是Python中的内置函数。 它将返回列表中给定元素的总数。 count()函数用于对列表中的元素以及字符串进行计数。

语法:

list.count(element)

参数:

element:是我们要查找计数的元素.

返回值:

count()方法将返回一个整数值,即给定列表中给定元素的计数。 如果在给定列表中找不到该值,则返回0.

示例1:列表计数

以下示例显示了list()函数的工作方式:

list1 = ['red', 'green', 'blue', 'orange', 'green', 'gray', 'green']
color_count = list1.count('green')
print('The count of color: green is ', color_count)

输出:

The count of color: green is  3

示例2:查找给定列表中的元素计数(重复项)

list1 = [2,3,4,3,10,3,5,6,3]
elm_count = list1.count(3)
print('The count of element: 3 is ', elm_count)

输出:

The count of element: 3 is  4

总结

count()是Python中的内置函数。 它将返回列表或字符串中给定元素的个数。

对于列表,需要将计数的元素传递给count()函数,它将返回该元素的个数。

count()方法返回一个整数值。

以上就是关于count()方法的全部内容了,如需了解更多python实用知识,点击进入PyThon学习网教学中心

关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图