Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1790173
  • 博文数量: 297
  • 博客积分: 285
  • 博客等级: 二等列兵
  • 技术积分: 3006
  • 用 户 组: 普通用户
  • 注册时间: 2010-03-06 22:04
个人简介

Linuxer, ex IBMer. GNU https://hmchzb19.github.io/

文章分类

全部博文(297)

文章存档

2020年(11)

2019年(15)

2018年(43)

2017年(79)

2016年(79)

2015年(58)

2014年(1)

2013年(8)

2012年(3)

分类: Python/Ruby

2016-04-13 16:42:24

办法太多。下面代码里面有4种办法。3种使用字典,一个办法使用list。

点击(此处)折叠或打开

  1. def char_freq(sentence):
  2.     frequencies={}
  3.     for letter in sentence:
  4.         frequency=frequencies.setdefault(letter,0)
  5.         frequencies[letter]+=1
  6.     return frequencies

  7. from collections import defaultdict
  8. def char_freq2(sentence):
  9.     frequencies=defaultdict(int)
  10.     for letter in sentence:
  11.         frequencies[letter]+=1
  12.     return frequencies

  13. from collections import Counter
  14. def char_freq3(sentence):
  15.     return Counter(sentence)

  16. zen="""Beautiful is better than ugly.
  17. Explicit is better than implicit.
  18. Simple is better than complex.
  19. Complex is better than complicated.
  20. Flat is better than nested.
  21. Sparse is better than dense.
  22. Readability counts.
  23. Special cases aren't special enough to break the rules.
  24. Although practicality beats purity.
  25. Errors should never pass silently.
  26. Unless explicitly silenced.
  27. In the face of ambiguity, refuse the temptation to guess.
  28. There should be one-- and preferably only one --obvious way to do it.
  29. Although that way may not be obvious at first unless you're Dutch.
  30. Now is better than never.
  31. Although never is often better than *right* now.
  32. If the implementation is hard to explain, it's a bad idea.
  33. If the implementation is easy to explain, it may be a good idea.
  34. Namespaces are one honking great idea -- let's do more of those!"""

  35. #use list to get the character frequency
  36. import string
  37. CHARACTERS=list(string.ascii_letters+string.punctuation)+[" "]
  38. def letter_freq(sentence):
  39.     frequencies=[(c,0) for c in CHARACTERS]
  40.     for letter in sentence:
  41.         index=CHARACTERS.index(letter)
  42.         frequencies[index]=(letter,frequencies[index][1]+1)
  43.     return frequencies

  44. def test_char_frq():
  45.     dict1=char_freq(zen)
  46.     print([(k,dict1[k]) for k in sorted(dict1)])
  47.     dict2=char_freq2(zen)
  48.     print(dict1==dict2)
  49.     dict3=char_freq3(zen)
  50.     print(dict1==dict2==dict3)
  51.     #zen_strip=zen.translate(str.maketrans(" "," ",string.punctuation+string.whitespace))
  52.     zen_strip=zen.translate(str.maketrans(" "," ",string.whitespace))
  53.     print(letter_freq(zen_strip.strip()))

  54. test_char_frq()
下面转自别人的博客,对字典排序。
对字典的排序,无非是通过keys,或者values 排序。python的排序是stable的。dict的key本身不会重复,但是value是会重复的。

点击(此处)折叠或打开


  1. #-------------------sort dict---------------------------------
  2. #sorted by key
  3. def sortdict(adict):
  4.     items=list(adict.items())
  5.     items.sort()
  6.     return [(key,value) for key,value in items]

  7. #sorted by key too
  8. def sortdict2(adict):
  9.     keys=list(adict.keys())
  10.     keys.sort()
  11.     return [(key,adict[key]) for key in keys]
  12.     #return list(map(adict.get,keys))
  13.     #with map only return value

  14. #sorted by value
  15. def sortdict3(adict):
  16.     items=list(adict.items())
  17.     backitems=[[v[1],v[0]] for v in items]
  18.     backitems.sort()
  19.     return [(backitems[i][0],backitems[i][1]) for i in range(0,len(backitems))]


  20. #sorted with list comprehension & lambda
  21. def sorted_with_list_comprehension(adict):
  22.     sorted_dict=[(k,adict[k]) for k in sorted(adict)] #sort by key
  23.     sorted_dict=sorted(adic1.items(),key=lambda x:x[0]) #sort by key
  24.     sorted_dict=sorted(adict.items(),key=lambda x:x[1]) #sort by value
  25.     return sorted_dict

  26. #or we can use OrderedDict , OrderDict remember the keys were first inserted
  27. #example from https://docs.python.org/3/library/collections.html#collections.OrderedDict
  28. from collections import OrderedDict

  29. def sort_orderdict():
  30.     d={'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}
  31.     print(OrderedDict(sorted(d.items(), key=lambda t: t[0]))) #sorted by key
  32.     print(OrderedDict(sorted(d.items(), key=lambda t: t[1]))) #sorted by value
  33.     print(OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))) #sorted by length of the key string
最后对类排序,感叹一下,python的syntax sugar 真强大。

点击(此处)折叠或打开

  1. #-----------------sort object ----------------------------------------------------------------------
  2. class WeirdSortee:
  3.     def __init__(self,string,number,sort_num=False):
  4.         self.string=string
  5.         self.number=number
  6.         self.sort_num=sort_num

  7.     def __lt__(self,other):
  8.         if self.sort_num:
  9.             return self.number < other.number
  10.         return self.string < other.string

  11.     def __repr__(self):
  12.         return "{}:{}".format(self.string,self.number)


  13. def test_weirdsort():
  14.     a=WeirdSortee('a',4,True)
  15.     b=WeirdSortee('b',3,True)
  16.     c=WeirdSortee('c',2,True)
  17.     d=WeirdSortee('d',1,True)
  18.     l=[a,b,c,d]
  19.     k=sorted(l)
  20.     print(k)
  21.     for i in l:
  22.         i.sort_num=False
  23.     k=sorted(l)
  24.     print(k)

  25. #test_weirdsort()

  26. """
  27. the class should normally also implement the similar __gt__, __
  28. eq__, __ne__, __ge__, and __le__ methods so that all of the <, >, ==, !=, >=, and <=
  29. operators also work properly. You can get this for free by implementing __lt__ and
  30. __eq__, and then applying the @total_ordering class decorator to supply the rest:
  31. """

  32. from functools import total_ordering

  33. @total_ordering
  34. class WeirdSortee2:
  35.     def __init__(self,string,number,sort_num=False):
  36.         self.string=string
  37.         self.number=number
  38.         self.sort_num=sort_num
  39.     
  40.     def __lt__(self,other):
  41.         if self.sort_num:
  42.             return self.number < other.number
  43.         return self.string < other.string

  44.     def __repr__(self):
  45.         return "{}:{}".format(self.string,self.number)

  46.     def __eq__(self,other):
  47.         return all((self.string==other.string,
  48.             self.number==other.number,
  49.             self.sort_num==other.sort_num
  50.             ))

  51. def test_weirdsort2():
  52.     a=WeirdSortee2('a',4,True)
  53.     b=WeirdSortee2('b',3,True)
  54.     c=WeirdSortee2('c',2,True)
  55.     d=WeirdSortee2('d',1,True)
  56.     print("sort by number a>b:",a>b)
  57.     print("sort by number a==b:",a==b)
  58.     print("sort by number a>=b:",a>=b)
  59.     print("sort by number a<=b:",a<=b)
  60.     print("sort by number a,a<b)



阅读(1158) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~