python 統計單詞個數,並按個數與字母排序


# coding: utf-8

# In[1]:

import collections

str = "Be slow to promise and quick to perform"
# 按空格切割
str_split = str.split(' ')


# In[2]:

str_split

# Out[2]:
#['Be', 'slow', 'to', 'promise', 'and', 'quick', 'to', 'perform']

# In[3]:

# 統計每個單詞的個數
temp_str = collections.Counter(str_split).most_common()
temp_str

# Out[3]:
# [('to', 2),
#  ('and', 1),
#  ('Be', 1),
#  ('slow', 1),
#  ('perform', 1),
#  ('promise', 1),
#  ('quick', 1)]

# In[4]:

# 排序方式用lambda ,先排個數,再按字母順序排
sorted(temp_str, key = lambda x:[-x[1],x[0]])

# Out[4]:
# [('to', 2),
#  ('Be', 1),
#  ('and', 1),
#  ('perform', 1),
#  ('promise', 1),
#  ('quick', 1),
#  ('slow', 1)]

 


免責聲明!

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



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