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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值