python練習:一行搞定-統計一句話中每個單詞出現的個數


一行搞定-統計一句話中每個單詞出現的個數

>>> s
'i am a boy a bood boy a bad boy'

方式一:
>>> dict([(i,s.split().count(i)) for i in s.split()])
{'a': 3, 'boy': 3, 'i': 1, 'am': 1, 'bad': 1, 'bood': 1}

>>> set([(i,s.split().count(i)) for i in s.split()])
set([('boy', 3), ('am', 1), ('i', 1), ('bood', 1), ('a', 3), ('bad', 1)])

方式二:

>>> set(map(lambda x:(x,s.split().count(x)),s.split()))
set([('boy', 3), ('am', 1), ('i', 1), ('bood', 1), ('a', 3), ('bad', 1)])

>>> dict(map(lambda x:(x,s.split().count(x)),s.split()))
{'a': 3, 'boy': 3, 'i': 1, 'am': 1, 'bad': 1, 'bood': 1}


免責聲明!

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



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