python字典统计排序代码_005_004 Python 统计值 并按照次数排序 可以通过字典的值对key进行排序 | 学步园...

该博客介绍了如何使用Python的字典和列表实现计数排序,并提供了示例代码。首先通过字典类`hist`实现了计数排序,然后通过列表类`histlist`进行了相同功能的实现。此外,还展示了如何对字符串中的单词进行计数,并按升序和降序输出。最后,使用`itemgetter`对字典的值进行排序。
摘要由CSDN通过智能技术生成

代码如下:

#encoding=utf-8

print '中国'

#统计值 并按照次数排序 可以通过字典的值对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 hist1

sentence = ''' 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值