发布于 2014-09-28 05:20:01 | 177 次阅读 | 评论: 0 | 来源: 网友投递
这里有新鲜出炉的Python3 官方中文指南,程序狗速度看过来!
Python编程语言
Python 是一种面向对象、解释型计算机程序设计语言,由Guido van Rossum于1989年底发明,第一个公开发行版发行于1991年。Python语法简洁而清晰,具有丰富和强大的类库。它常被昵称为胶水语言,它能够把用其他语言制作的各种模块(尤其是C/C++)很轻松地联结在一起。
这篇文章主要介绍了python实现在无须过多援引的情况下创建字典的方法,是非常实用的技巧,需要的朋友可以参考下
python实现在无须过多援引的情况下创建字典的方法如下:
1.使用itertools模块
import itertools the_key = ['ab','22',33] the_vale = ['aaaa',"dddddddd",'22222222222'] d = dict(itertools.izip(the_key,the_vale)) print d
2.加参数
dict = dict(red = 1,bule = 2,yellow = 3) print dict
结果为:{'yellow': 3, 'bule': 2, 'red': 1}
3.使用内置的zip函数
zip([iterable,...])返回一个列表,
the_key = ['ab','22',33] the_vale = ['aaaa',"dddddddd",'22222222222'] dict2 = dict(zip(the_key,the_vale)) print type(zip(the_key,the_vale)) print dict2
结果:
<type 'list'> {33: '22222222222', 'ab': 'aaaa', '22': 'dddddddd'}
4.dict的fromkeys函数
创建的每个键有相同的value
fromkeys(seq[,value]) Create a new dictionary with keys from seq and values set to value. the_key = ['ab','22',33] the_vale = 0 d = dict.fromkeys(the_key,the_vale) print
结果:{33: 0, 'ab': 0, '22': 0}
import string count_by_letter = dict.fromkeys(string.ascii_lowercase,0) print count_by_letter
结果:
{'a': 0, 'c': 0, 'b': 0, 'e': 0, 'd': 0, 'g': 0, 'f': 0, 'i': 0, 'h': 0, 'k': 0, 'j': 0, 'm': 0, 'l': 0, 'o': 0, 'n': 0, 'q': 0, 'p': 0, 's': 0, 'r': 0, 'u': 0, 't': 0, 'w': 0, 'v': 0, 'y': 0, 'x': 0, 'z': 0}