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)]
相關文章
相關標籤/搜索