Home > Backend Development > Python Tutorial > python从入门到精通(DAY 2)

python从入门到精通(DAY 2)

WBOY
Release: 2016-06-10 15:06:56
Original
1420 people have browsed it

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  深复制(完全独立)

Copy after login

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

例:

>>> 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)

Copy after login

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

>>> 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'}

Copy after login

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

>>> 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'}

Copy after login

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

>>> 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'}

Copy after login

2、内置函数说明:

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

__file__:文件的绝对路径;

__doc__:文件开头的注释说明

例:

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

if __name__ == '__main__':
  print('this is main file')
  print(__file__)
  print(__doc__)
Copy after login

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template