办法太多。下面代码里面有4种办法。3种使用字典,一个办法使用list。
-
def char_freq(sentence):
-
frequencies={}
-
for letter in sentence:
-
frequency=frequencies.setdefault(letter,0)
-
frequencies[letter]+=1
-
return frequencies
-
-
from collections import defaultdict
-
def char_freq2(sentence):
-
frequencies=defaultdict(int)
-
for letter in sentence:
-
frequencies[letter]+=1
-
return frequencies
-
-
from collections import Counter
-
def char_freq3(sentence):
-
return Counter(sentence)
-
-
zen="""Beautiful is better than ugly.
-
Explicit is better than implicit.
-
Simple is better than complex.
-
Complex is better than complicated.
-
Flat is better than nested.
-
Sparse is better than dense.
-
Readability counts.
-
Special cases aren't special enough to break the rules.
-
Although practicality beats purity.
-
Errors should never pass silently.
-
Unless explicitly silenced.
-
In the face of ambiguity, refuse the temptation to guess.
-
There should be one-- and preferably only one --obvious way to do it.
-
Although that way may not be obvious at first unless you're Dutch.
-
Now is better than never.
-
Although never is often better than *right* now.
-
If the implementation is hard to explain, it's a bad idea.
-
If the implementation is easy to explain, it may be a good idea.
-
Namespaces are one honking great idea -- let's do more of those!"""
-
-
#use list to get the character frequency
-
import string
-
CHARACTERS=list(string.ascii_letters+string.punctuation)+[" "]
-
def letter_freq(sentence):
-
frequencies=[(c,0) for c in CHARACTERS]
-
for letter in sentence:
-
index=CHARACTERS.index(letter)
-
frequencies[index]=(letter,frequencies[index][1]+1)
-
return frequencies
-
-
def test_char_frq():
-
dict1=char_freq(zen)
-
print([(k,dict1[k]) for k in sorted(dict1)])
-
dict2=char_freq2(zen)
-
print(dict1==dict2)
-
dict3=char_freq3(zen)
-
print(dict1==dict2==dict3)
-
#zen_strip=zen.translate(str.maketrans(" "," ",string.punctuation+string.whitespace))
-
zen_strip=zen.translate(str.maketrans(" "," ",string.whitespace))
-
print(letter_freq(zen_strip.strip()))
-
-
test_char_frq()
下面转自别人的博客,对字典排序。
对字典的排序,无非是通过keys,或者values 排序。python的排序是stable的。dict的key本身不会重复,但是value是会重复的。
-
-
#-------------------sort dict---------------------------------
-
#sorted by key
-
def sortdict(adict):
-
items=list(adict.items())
-
items.sort()
-
return [(key,value) for key,value in items]
-
-
#sorted by key too
-
def sortdict2(adict):
-
keys=list(adict.keys())
-
keys.sort()
-
return [(key,adict[key]) for key in keys]
-
#return list(map(adict.get,keys))
-
#with map only return value
-
-
#sorted by value
-
def sortdict3(adict):
-
items=list(adict.items())
-
backitems=[[v[1],v[0]] for v in items]
-
backitems.sort()
-
return [(backitems[i][0],backitems[i][1]) for i in range(0,len(backitems))]
-
-
-
#sorted with list comprehension & lambda
-
def sorted_with_list_comprehension(adict):
-
sorted_dict=[(k,adict[k]) for k in sorted(adict)] #sort by key
-
sorted_dict=sorted(adic1.items(),key=lambda x:x[0]) #sort by key
-
sorted_dict=sorted(adict.items(),key=lambda x:x[1]) #sort by value
-
return sorted_dict
-
-
#or we can use OrderedDict , OrderDict remember the keys were first inserted
-
#example from https://docs.python.org/3/library/collections.html#collections.OrderedDict
-
from collections import OrderedDict
-
-
def sort_orderdict():
-
d={'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}
-
print(OrderedDict(sorted(d.items(), key=lambda t: t[0]))) #sorted by key
-
print(OrderedDict(sorted(d.items(), key=lambda t: t[1]))) #sorted by value
-
print(OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))) #sorted by length of the key string
最后对类排序,感叹一下,python的syntax sugar 真强大。
-
#-----------------sort object ----------------------------------------------------------------------
-
class WeirdSortee:
-
def __init__(self,string,number,sort_num=False):
-
self.string=string
-
self.number=number
-
self.sort_num=sort_num
-
-
def __lt__(self,other):
-
if self.sort_num:
-
return self.number < other.number
-
return self.string < other.string
-
-
def __repr__(self):
-
return "{}:{}".format(self.string,self.number)
-
-
-
def test_weirdsort():
-
a=WeirdSortee('a',4,True)
-
b=WeirdSortee('b',3,True)
-
c=WeirdSortee('c',2,True)
-
d=WeirdSortee('d',1,True)
-
l=[a,b,c,d]
-
k=sorted(l)
-
print(k)
-
for i in l:
-
i.sort_num=False
-
k=sorted(l)
-
print(k)
-
-
#test_weirdsort()
-
-
"""
-
the class should normally also implement the similar __gt__, __
-
eq__, __ne__, __ge__, and __le__ methods so that all of the <, >, ==, !=, >=, and <=
-
operators also work properly. You can get this for free by implementing __lt__ and
-
__eq__, and then applying the @total_ordering class decorator to supply the rest:
-
"""
-
-
from functools import total_ordering
-
-
@total_ordering
-
class WeirdSortee2:
-
def __init__(self,string,number,sort_num=False):
-
self.string=string
-
self.number=number
-
self.sort_num=sort_num
-
-
def __lt__(self,other):
-
if self.sort_num:
-
return self.number < other.number
-
return self.string < other.string
-
-
def __repr__(self):
-
return "{}:{}".format(self.string,self.number)
-
-
def __eq__(self,other):
-
return all((self.string==other.string,
-
self.number==other.number,
-
self.sort_num==other.sort_num
-
))
-
-
def test_weirdsort2():
-
a=WeirdSortee2('a',4,True)
-
b=WeirdSortee2('b',3,True)
-
c=WeirdSortee2('c',2,True)
-
d=WeirdSortee2('d',1,True)
-
print("sort by number a>b:",a>b)
-
print("sort by number a==b:",a==b)
-
print("sort by number a>=b:",a>=b)
-
print("sort by number a<=b:",a<=b)
-
print("sort by number a,a<b)
阅读(1149) | 评论(0) | 转发(0) |