首页 > 编程语言 > 详细

python学习笔记(第二天)

时间:2015-12-20 00:33:57      阅读:298      评论:0      收藏:0      [点我收藏+]

 

1、字典复制:

dict = {‘name‘:‘wang‘, ‘sex‘:‘m‘, ‘age‘:34, ‘job‘:‘it‘}

info = dict            ##别名 (二个字典指向内存的同一地址空间)

info1 = dict.copy()    #shadow copy 浅复制(嵌套字典第一层独立,第二层以下相关联)

import copy

copy.copy()            #shadow copy 浅复制

copy.deepcopy()        #deep copy   深复制(完全独立)

注:浅复制下的关联只是针对字典初始状态包含的嵌套对象,后新加的不会

例:


>>> dict
{‘info‘: [‘a‘, ‘b‘, 1, 2], ‘job‘: ‘it‘, ‘sex‘: ‘m‘, ‘age‘: 40, ‘name‘: ‘wang‘}
>>> dict_alias = dict
>>> dict_copy = copy.copy(dict)
>>> dict_deep = copy.deepcopy(dict)


#添加、改变、删除第一层的对象键值,浅复制和深复制都不受影响

>>> dict[‘age‘] = 32

>>> del dict[‘sex‘]
>>> dict
{‘info‘: [‘a‘, ‘b‘, 1, 2], ‘job‘: ‘it‘, ‘age‘: 32, ‘name‘: ‘wang‘}
>>> dict_alias     
{‘info‘: [‘a‘, ‘b‘, 1, 2], ‘job‘: ‘it‘, ‘age‘: 32, ‘name‘: ‘wang‘}
>>> dict_copy      
{‘info‘: [‘a‘, ‘b‘, 1, 2], ‘job‘: ‘it‘, ‘age‘: 40, ‘name‘: ‘wang‘, ‘sex‘: ‘m‘}
>>> dict_deep      
{‘info‘: [‘a‘, ‘b‘, 1, 2], ‘job‘: ‘it‘, ‘age‘: 40, ‘name‘: ‘wang‘, ‘sex‘: ‘m‘}


#改变、删除原有的第二层的对象键值,浅复制受影响,而深复制都不受影响

>>> dict[‘info‘][2] = 100
>>> dict
{‘info‘: [‘a‘, ‘b‘, 100, 2], ‘job‘: ‘it‘, ‘age‘: 32, ‘name‘: ‘wang‘}
>>> dict_alias
{‘info‘: [‘a‘, ‘b‘, 100, 2], ‘job‘: ‘it‘, ‘age‘: 32, ‘name‘: ‘wang‘}
>>> dict_copy
{‘info‘: [‘a‘, ‘b‘, 100, 2], ‘job‘: ‘it‘, ‘age‘: 40, ‘name‘: ‘wang‘, ‘sex‘: ‘m‘}
>>> dict_deep
{‘info‘: [‘a‘, ‘b‘, 1, 2], ‘job‘: ‘it‘, ‘age‘: 40, ‘name‘: ‘wang‘, ‘sex‘: ‘m‘}


#添加第二层的对象,浅复制和深复制都不受影响

>>> dict[‘new‘] = {‘a‘:1, ‘b‘:2, ‘c‘:5}
>>> dict
{‘info‘: [‘a‘, ‘b‘, 100, 2], ‘name‘: ‘wang‘, ‘age‘: 32, ‘job‘: ‘it‘, ‘new‘: {‘a‘: 1, ‘c‘: 5, ‘b‘: 2}}
>>> dict_alias
{‘info‘: [‘a‘, ‘b‘, 100, 2], ‘name‘: ‘wang‘, ‘age‘: 32, ‘job‘: ‘it‘, ‘new‘: {‘a‘: 1, ‘c‘: 5, ‘b‘: 2}}
>>> dict_copy
{‘info‘: [‘a‘, ‘b‘, 100, 2], ‘job‘: ‘it‘, ‘age‘: 40, ‘name‘: ‘wang‘, ‘sex‘: ‘m‘}
>>> dict_deep
{‘info‘: [‘a‘, ‘b‘, 1, 2], ‘job‘: ‘it‘, ‘age‘: 40, ‘name‘: ‘wang‘, ‘sex‘: ‘m‘}


 

2、内置函数说明:

      __name__:主文件时返回main,否则返回文件名,可用来判断是否说主文件还是导入模块;

      __file__:文件的绝对路径;

      __doc__:文件开头的注释说明

例:

‘‘‘
    created by 2015-12-18
    @author: kevin
‘‘‘


if __name__ == ‘__main__‘:
    print(‘this is main file‘)
    print(__file__)
    print(__doc__)

python学习笔记(第二天)

原文:http://www.cnblogs.com/wushank/p/5060023.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!