Operator.countOf()
用於計數出現的次數b
在a
。它計算值的出現次數。
用法: Operator.countOf(freq = a, value = b)
參數:
freq: It can be list or any other data type which store value
value: It is value for which we have to count the number of occurrences
返回值:值出現次數的計數。
範例1:采用Operator.countOf()
計算列表中給定值的出現次數。
# Python program showing
# use of countOf() function
# in a list
from operator import *
arr = [ 1, 2, 3, 3, 3 ]
arr1 = [ 'a', 'b', 'c', 'b', 'd' ]
print("Number of occurrence of b in arr1 =", countOf(arr1, "b"))
print("Number of occurrence of e in arr1 =", countOf(arr1, "e"))
print("Number of occurrence of 3 in arr =", countOf(arr, 3))
輸出:
Number of occurrence of b in arr1 = 2 Number of occurrence of e in arr1 = 0 Number of occurrence of 3 in arr = 3
範例2:采用Operator.countOf()
計算字典中給定值的出現次數。
# Python program showing
# use of countOf() function
# in a dictionary
from operator import *
d = {"score":3, "score1":1, "score2":3, "score3":1, "score4":3}
print("Number of occurrence of three in dict =",countOf(d.values(),3))
print("Number of occurrence of one in dict =",countOf(d.values(),1))
print("Number of occurrence of four in dict =",countOf(d.values(),4))
輸出:
Number of occurrence of three in dict = 3 Number of occurrence of one in dict = 2 Number of occurrence of four in dict = 0
範例3:采用Operator.countOf()
計算元組中給定值出現的次數。
# Python program showing
# use of countOf() function
# in a tuples
from operator import *
tup = ( 1, 2, 3, 3, 3 )
tup1 = ( 'a', 'b', 'c', 'b', 'd' )
print("Number of occurrence of b in tuple1 =",countOf(tup1,"b"))
print("Number of occurrence of e in tuple1 =",countOf(tup1,"e"))
print("Number of occurrence of 3 in tuple =",countOf(tup,3))
輸出:
Number of occurrence of b in tuple1 = 2 Number of occurrence of e in tuple1 = 0 Number of occurrence of 3 in tuple = 3
相關用法
注:本文由純淨天空篩選整理自garg_ak0109大神的英文原創作品 Python | Operator.countOf。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。