005_004 Python 统计值 并按照次数排序 可以通过字典的值对key进行排序
来源:互联网 发布:小白基地源码论坛 编辑:程序博客网 时间:2024/05/12 01:09
代码如下:
#encoding=utf-8print '中国'#统计值 并按照次数排序 可以通过字典的值对key进行排序#通过字典来实现class hist(dict): def add(self,item,increment=1): self[item]=increment + self.get(item,0) def counts(self,reverse=False): aux=[(self[k],k) for k in self] aux.sort(cmp=None, key=None, reverse=False) if reverse: aux.reverse() return [k for v,k in aux]hist1=hist()hist1.add(3)hist1.add(3)hist1.add(1)print hist1.counts()#通过list来实现class histlist(list): def __init__(self,n): list.__init__(self,n*[0]) def add(self,item,increment=1): self[item] += increment def counts(self,reverse=False): aux=[(v,k) for k,v in enumerate(self)] aux.sort(cmp=None, key=None, reverse=False) if reverse:aux.reverse() return [k for v,k in aux] hist1=histlist(4)hist1.add(3)hist1.add(3)hist1.add(1)print hist1sentence = ''' Hello there this is a test. Hello there this was a test, but now it is not. '''words = sentence.split( )c = hist( )for word in words: c.add(word)print "Ascending count:"print c.counts( )print "Descending count:"print c.counts(reverse=True)from operator import itemgetter#itemgetter为获取当前维度的值 (key,val) val为维度一 排序当前维度的值def dict_items_sorted_by_value(d, reverse=False): return sorted(d.iteritems( ), key=itemgetter(1), reverse=reverse)print dict_items_sorted_by_value(c)打印结果如下:
中国
[1, 3]
[0, 1, 0, 2]
Ascending count:
['but', 'it', 'not.', 'now', 'test,', 'test.', 'was', 'Hello', 'a', 'is', 'there', 'this']
Descending count:
['this', 'there', 'is', 'a', 'Hello', 'was', 'test.', 'test,', 'now', 'not.', 'it', 'but']
[('not.', 1), ('it', 1), ('but', 1), ('test,', 1), ('now', 1), ('was', 1), ('test.', 1), ('a', 2), ('this', 2), ('is', 2), ('there', 2), ('Hello', 2)]
0 0
- 005_004 Python 统计值 并按照次数排序 可以通过字典的值对key进行排序
- python 按照字典的值进行排序
- Java按照key值字典排序进行MD5加密
- python字典按照值排序
- 按照参数key或value值进行字典排序的两种java算法实现
- Python高效编程-对字典的值进行排序
- python 统计数组中元素出现次数并进行排序
- 将对象数组按照每一组对象的key值大小进行字典顺序(ASCII值大小)升序排序
- iOS 字典按照key的排序
- python字典排序、按照list中的字典的某个key排序
- python通过对字典的排序,对json字段进行排序
- [python]对字典进行排序
- python 对字典进行排序
- iOS 对字典的key,value进行排序
- iOS中对字典的key进行排序
- 统计 数据中 重复值的次数( 另外,可再对其进行排序,重复次数多的在前边
- python3.5对字典按照key/value排序
- 根据字典的值大小对字典进行排序
- 枚举和字符串互转
- Hello !
- Linux下MySQL常用操作网络汇总总结
- 【servlet】servlet 笔记
- java线程并发
- 005_004 Python 统计值 并按照次数排序 可以通过字典的值对key进行排序
- 10种软件滤波方法的示例程序
- VC对话框全屏显示及相应控件位置改变
- apk
- 揭秘:恒生电子到底是干什么的
- 树莓派初级折腾
- 处理二进制表单数据
- OCUnit异步测试
- 数据库事务隔离级别+Spring 声明性事务隔离级别