1.用count()函數(對字符串\列表\元組進行計數)
list_japan = [1,2,3,4,5,4,3,5,2,2]
for i in set(list_japan):
#count函數某一個字符在列表中的出現次數
print(f"{
i}出現{
list_japan.count(i)}次")
2.用Counter類(對字符串\列表\元組\字典進行計數)
list_japan = [1,2,3,4,5,4,3,5,2,2]
from collections import Counter
# 對字符串\列表\元祖\字典進行計數,返回一個字典類型的數據,鍵是元素,值是元素出現的次數
print(Counter(list_japan))
python字典中不允許同一個鍵出現兩次。創建時如果同一個鍵被賦值兩次,後一個值會被記住
3.用雙層循環計數
list_japan =[1,4,2,4,2,2,5,2,6,3,3,6,3,6,6,3,3,3,7,8,9,8,7,0,7,1,2,4,7,8,9]
dicc = {
}
count = 0
for i in set(list_japan):
for j in list_japan:
if i==j:
count+=1
dicc[i]=count
count=0
print(dicc)