python3 开发面试题(字典和拷贝)5.30

Posted manyqian

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python3 开发面试题(字典和拷贝)5.30相关的知识,希望对你有一定的参考价值。

"""
问:执行完下面的代码后,  l,m的内容分别是什么?
"""


def func(m):
    for k,v in m.items():
        m[k+2] = v+2


m = {1: 2, 3: 4}
l = m  # 拷贝
l[9] = 10
func(l)
m[7] = 8


print("l:", l)
print("m:", m)
技术分享图片
#在python 3.6版本 以上会直接报错

#在迭代一个列表或字典的时候,你不能修改列表或字典的大小!


#在python 2.6版本中,得出的结果是一样的:
l浅拷贝m,引用的是同一个内存地址,而且他们的值都发生变化 

print l
{1: 2, 3: 4, 5: 6, 7: 8, 9: 10, 11: 12}
print m
{1: 2, 3: 4, 5: 6, 7: 8, 9: 10, 11: 12}

#PS:旧版本的python就要停止服务,所以现版本还是比较好的!
答案
# = 、 切片 、copy 、deepcopy

import copy

list1 = [11, 22, [33, 44]]
list2 = list1
list3 = list1[:]
list4 = copy.copy(list1)
list4 = copy.copy(list1)
list5 = copy.deepcopy(list1)

list1[2].append(55)
print("list2:",list2)  # [11, 22, [33, 44, 55]]
print("list3:",list3)  # [11, 22, [33, 44, 55]]
print("list4:",list4)  # [11, 22, [33, 44, 55]]
print("list5:",list5)  # [11, 22, [33, 44]]

#除了deepcopy不是浅拷贝,别的方式都是引用的同一内存地址
#而deepcopy单独开辟新的内存空间

 

以上是关于python3 开发面试题(字典和拷贝)5.30的主要内容,如果未能解决你的问题,请参考以下文章

Python面试题及答案汇总

python3 开发面试题(面向对象)6.6

python3 开发面试题(%s和format的区别)5.31

python3 开发面试题(生成列表)6.1

python3-开发面试题(python)6.23基础篇

python3 开发面试题(创建表结构)6.9