鱼C论坛

 找回密码
 立即注册
查看: 2772|回复: 1

[技术交流] 《零基础入门学习Python》第26课笔记

[复制链接]
发表于 2015-4-11 18:18:39 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
字典的内建方法:


1.      fromkeys ()


>>> dict1.fromkeys((1,2,3))


{1: None, 2: None, 3: None}


>>>dict1.fromkeys((1,2,3),'number')


{1: 'number', 2: 'number', 3: 'number'}


>>> dict1.fromkeys((1,2,3),('one','two','three'))


{1: ('one', 'two', 'three'), 2: ('one','two', 'three'), 3: ('one', 'two', 'three')}




2. 访问字典的方法:


(1)keys:


>>> dict1 =dict1.fromkeys(range(5),'')


>>> dict1


{0: '', 1: '', 2: '', 3: '', 4: ''}


>>> for eachkey in dict1.keys():


       print(eachkey)


0


1


2


3


4


(2) values


>>> for eachvalue indict1.values():


       print(eachvalue)












(3) items ()


>>> for eachitem in dict1.items():


       print(eachitem)


(0,'')


(1, '')


(2, '')


(3, '')


(4, '')




如果不知道字典中是否有此值,可以用in 或者 not in


>>> 4 in dict1


True


>>> 5 in dict1


False

当数据规模很大的时候,字典和序列查找的效率有较大差别,字典高效。在字典里查找的是键,而在序列里查找的是元素的值而不是元素的索引号。

(4). 清空字典 clear ( )


>>> dict1


{0: '', 1: '', 2: '', 3: '', 4: ''}


>>> dict1.clear()


>>> dict1


{}




(5). Copy()


>>> a ={1:'one',2:'two',3:'three'}


>>> b = a.copy()


>>> c = a


>>> c


{1: 'one', 2: 'two', 3: 'three'}


>>> b


{1: 'one', 2: 'two', 3: 'three'}


>>> id(a)       # ac地址一样。


55314824


>>> id(b)       #ab地址一样


55415880


>>> id(c)


55314824




(6) pop ( )


>>> a.pop(2)


'two'


>>> a


{1: 'one', 3: 'three'}


>>> a.popitem()        #随机弹出字典元素


(1, 'one')




(7) setdefault ( )


>>> a ={1:'one',2:'two',3:'three'}


>>> a


{1: 'one', 2: 'two', 3: 'three'}


>>> a.setdefault(4,'小白')


'小白'


>>> a


{1: 'one', 2: 'two', 3: 'three', 4: '小白'}


(8) update ( )


>>> b = {'小白':''}


>>> a.update(b)


>>> a


{1: 'one', 2: 'two', 3: 'three', 4: '小白', '小白': ''}


想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2015-4-11 18:47:08 | 显示全部楼层
自学能力太强悍了,,好嫉妒,555555
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-27 09:15

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表