程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python counts the number of occurrences of repeating elements in the list

編輯:Python

1. use count() function ( The string \ list \ Count tuples )

list_japan = [1,2,3,4,5,4,3,5,2,2]
for i in set(list_japan):
#count Function the number of times a character appears in the list 
print(f"{
i} appear {
list_japan.count(i)} Time ")

2. use Counter class ( The string \ list \ Tuples \ The dictionary counts )

list_japan = [1,2,3,4,5,4,3,5,2,2]
from collections import Counter
# The string \ list \ Yuan Zu \ The dictionary counts , Returns data of a dictionary type , Keys are elements , The value is the number of times the element appears 
print(Counter(list_japan))

python The same key is not allowed to appear twice in the dictionary . When creating, if the same key is assigned twice , The latter value will be remembered
3. Count with double-layer cycle

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)

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved