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