Python--字典

打印一组字母串中每个字母出现的频率

1, 列表方案解决:

>>> s = 'abcefdddfffsss'
>>> lst = [0]*26 #生成26位的list,初始值为0
>>> for i in s:
...     lst[ord(i) - 97] += 1  #用ord()将字符串格式转化成ASII - 97 为方便list计数
...     
>>> print lst
[1, 1, 1, 3, 1, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0]

2, 字典解决方案

>>> count = {}
>>> for i in 'abcccdddfffeee':
...     if i in count:
...         count[i] += 1
...     else:
...         count[i] = 0
...         
>>> print count
{'a': 0, 'c': 2, 'b': 0, 'e': 2, 'd': 2, 'f': 2}

3,字典反转

>>> d1 = {'zhang':123, 'wang':456, 'zhao':123, 'guan':456}
>>> d2 = {}
>>> for name, room in d1.items():
...     if room in d2:
...         d2[room].append(name)
...     else:
...         d2[room] = [name]
...         
>>> print d2
{456: ['guan', 'wang'], 123: ['zhao', 'zhang']}

4, Python 字典(Dictionary) items() 函数以列表返回可遍历的(键, 值) 元组数组。


 1 #!/usr/bin/env python
 2 # -*- coding: UTF-8 -*-
 3 
 4 f = open('VVPS-Test-ReasonResultAnalysis.txt')
 5 
 6 word_freq = {}
 7 
 8 for line in f:
 9     words = line.split() # split a line by blanks
10     for word in words:
11         if word in word_freq:
12             word_freq[word] += 1
13         else:
14             word_freq[word] = 1
15 word_freq_list = []
16 for word, freq in word_freq.items():
17     word_freq_list.append((freq, word)) # exchange the key and values.
18 word_freq_list.sort(reverse = True) # list sort function to sort the list
19 
20 for freq, word in word_freq_list:
21     print word, freq
22 
23 
24 f.close()


 
原文地址:https://www.cnblogs.com/brownz/p/8310472.html