鱼C论坛

 找回密码
 立即注册
查看: 2865|回复: 7

排序问题,当出现次数一样时,如何按照字母表顺序取值。

[复制链接]
发表于 2016-8-13 20:54:19 | 显示全部楼层 |阅读模式
5鱼币
本帖最后由 felix_du 于 2016-8-13 21:37 编辑

一个排序问题,取字符串中出现最多的n个单词,若出现次数一样,按字母表顺序往后排。
我的思路就是先将单词和出现的次数存入字典,然后通过排序,将出现次数最多的单词存入列表中。

现在的问题在于,我可以通过value排序后,无法保证出现同等次数的单词按照字母表顺序排列。求帮忙。



  1. """Count words."""

  2. def count_words(s, n):
  3.     """Return the n most frequently occuring words in s."""
  4.    
  5.     # TODO: Count the number of occurences of each word in s
  6.    
  7.     # TODO: Sort the occurences in descending order (alphabetically in case of ties)
  8.    
  9.     # TODO: Return the top n words as a list of tuples (<word>, <count>)
  10.     s_list = s.split()
  11.     lenth = len(s_list)
  12.     counters ={}
  13.     for i in range(lenth):
  14.         if s_list[i] in counters:
  15.             counters[s_list[i]] += 1
  16.         else:
  17.             counters[s_list[i]] = 1
  18.     counter_sort = sorted(counters.items(),key=lambda item:item[1],reverse =True)
  19.     top_n_list = []
  20.     for i in range(n):
  21.         top_n_list.append((counter_sort[i][0],counter_sort[i][1]))
  22.     top_n = tuple(top_n_list)
  23.    
  24.    
  25.     return top_n


  26. def test_run():
  27.     """Test count_words() with some inputs."""
  28.     print count_words("cat bat mat cat bat cat", 3)
  29.     print count_words("betty bought a bit of butter but the butter was bitter", 3)


  30. if __name__ == '__main__':
  31.     test_run()
复制代码



最佳答案

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2016-8-13 20:54:20 | 显示全部楼层
  1.     counter_sort = sorted(sorted(counters.items(),
  2.                                  key=lambda item:item[0]),
  3.                           key=lambda item:item[1],
  4.                           reverse =True)
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2016-8-13 21:27:38 | 显示全部楼层
加个if语句,判断ascii值的大小试试
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2016-8-13 21:54:19 | 显示全部楼层
暂时只想到一个比较麻烦的办法
把出现次数相同的单词放到一个列表里面,列表有一个方法sort()可对字符串排序
  1. >>> a = ['asdf','abc','aze','acd']
  2. >>> a.sort()
  3. >>> a
  4. ['abc', 'acd', 'asdf', 'aze']
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2016-8-13 23:23:02 | 显示全部楼层

非常感谢。这段代码好漂亮。版主v5
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2016-8-13 23:27:11 | 显示全部楼层
shuofxz 发表于 2016-8-13 21:54
暂时只想到一个比较麻烦的办法
把出现次数相同的单词放到一个列表里面,列表有一个方法sort()可对字符串排 ...

这个想法我也考虑过,但是感觉不好操作。需要切分列表,但是切分的首尾又需要确认。很麻烦,不好弄。
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2016-8-18 20:27:28 | 显示全部楼层
LZ好牛,这代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2016-8-20 15:49:44 | 显示全部楼层
向你学习
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2026-2-22 05:25

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表