python列表count()
时间:2020-02-23 14:42:54 来源:igfitidea点击:
在本教程中,我们将看到Python列表的count方法。
Python列表计数方法用于计算列表中元素的数量。
Python列表count示例
我们可以简单地使用Count方法查找列表中的元素的数量。
让我们在简单的例子的帮助下了解这一点。
list1=[1,2,3,2,3,2,2,3,4,4,1,1,2] print("Count of 1 in the list1:",list1.count(1)) print("Count of 2 in the list1:",list1.count(2)) print("Count of 3 in the list1:",list1.count(3)) print("Count of 4 in the list1:",list1.count(4))
输出:
Count of 1 in the list1: 3 Count of 2 in the list1: 5 Count of 3 in the list1: 3 Count of 4 in the list1: 2
我们还可以在举例的帮助下找到SET或者TOUPLE的数量。
list1=['one',{1,2},'three',{1,2}] print('Count of set {1,2}:',list1.count({1,2})) list2=['one',(3,4),'three',(3,4),(3,4)] print('Count of tuple (3,4) :',list2.count((3,4)))
输出:
Count of set {1,2}: 2 Count of tuple (3,4) : 3