python_統計字符串個數


#取出字符串中出現2次的字符串,使用count方法統計
def
two_zifuchuan(str): s=set() for i in str: if str.count(i)==2: s.add(i) return s #取出字符串中出現2次的字符串,使用字典統計 def two_occur(str): s={} for i in str: if i in s.keys(): s[i]+=1 else: s[i]=1 return [i for i in s if s[i]==2] str="dddredddddewws22dff43" print(two_zifuchuan(str)) print(two_occur(str))

#統計數組中每個值的個數並打印且不能用count和字典,且時間換空間
li=[1,2,3,4,5,5,5,1,3,2,1] #數組
x=0
last=sorted(li)[0] #排序后第一個值
for i,j in enumerate(sorted(li)): #遍歷排序數組
if j==last: #假如當前遍歷數組值和上一個值一樣
x+=1 #個數加1
else:
print("%s的次數是:%s" % (last,x)) #當前遍歷數組和上一個值不同,輸出值及個數
x=1 #個數歸1
last=j #當前值遍歷給last

print("%s的次數是:%s" % (last, x))#輸出數組最后一個值的個數

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM