python實驗二:字串排序

來源:互聯網
上載者:User

標籤:odi   app   字串   saas   asa   sorted   list   []   while   

##統計word中的各個字元的出現的次數,並統計出所有前十名的字元使用次數
# -*- coding:utf-8 -*-word=‘‘‘awfesdafhjkcasadckjsdackjsadvcnksausafdschfsadfdsaasdfsdacsafsdaascsaasfdasdfsdasfadfsdafsadfjtyurjryjghnkuitki‘‘‘list1 = list(word)  #將字串轉化為列表while ‘\n‘ in list1:#去掉列表中的‘\n‘字元list1.remove(‘\n‘)list2 = sorted(list1)#列表排序list3 = list(set(list1))#列表去重複list4 = []#定義兩個空列表list5 = []for i in list3:j = list2.count(i)#統計字元個數list4.append((i, j))#將字元及個數加入新列表def recmp(x, y):#定義一個排序函數與cmp函數輸出結果相反if x < y :return 1if x == y:return 0if x > y:return -1list4.sort(lambda x,y:recmp(x[1],y[1]))#根據第二關鍵詞排序list5 = list4[:10]#取出前十項print list5#輸出結果:[(‘a‘, 22), (‘s‘, 21), (‘d‘, 16), (‘f‘, 13), (‘c‘, 7), (‘k‘, 6), (‘j‘, 6), (‘h‘, 3), (‘u‘, 3), (‘i‘, 2)]

  

python實驗二:字串排序

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.