Python对深浅拷贝、生成器的理解以及举例

  • A+
所属分类:编程语言

Python对深浅拷贝、生成器的理解以及举例

1. 简答

说下对python深浅拷贝的理解。并有代码简单实现

# 可变对象:列表(list)字典(dict)集合(set)对象(Obeject)

# 不可变对象:数字(number)字符串(str)元组(tuple)布尔(bool)None

#

# 浅拷贝是对于一个对象的顶层拷贝,只是拷贝了引用,并没有拷贝内容

# 内层地址一样

# 外层地址:1.如果是可变的,地址不同2.如果是不可变的,地址相同

import copy

#列表

ls1 = [1,2,3]

ls2 = copy.copy(ls1)

print(id(ls2))

print(id(ls1))

#元组

ls1 = (1,2,3)

ls2 = copy.copy(ls1)

print(id(ls2))

print(id(ls1))

#多层

#外层地址不同,内层地址相同

ls1 = [1,2,3]

ls2 = [4,5,6]

ls3 = [ls2,ls1]

ls4 = copy.copy(ls3)

print(id(ls3))

print(id(ls4))

#外层地址一样,内层地址相同

ls1 = [1,2,3]

ls2 = [4,5,6]

ls3 = (ls2,ls1)

ls4 = copy.copy(ls3)

print(id(ls3))

print(id(ls4))

#外层地址一样,内层地址相同

ls1 = (1,2,3)

ls2 = (4,5,6)

ls3 = (ls2,ls1)

ls4 = copy.copy(ls3)

print(id(ls3))

print(id(ls4))

#外层地址不同,内层地址相同

ls1 = (1,2,3)

ls2 = (4,5,6)

ls3 = [ls2,ls1]

ls4 = copy.copy(ls3)

print(id(ls3))

print(id(ls4))

# 深拷贝是对于一个对象所有层次的拷贝

# 1.如果所有层都是不可变的,所有层地址相同

# 2.如果有一个是可变的,外层一定不同

# 3.如果内层中这一层是可变的,地址不同,否则:相同

# 地址不同

ls1 = [1,2,3]

ls2 = copy.deepcopy(ls1)

print(id(ls2))

print(id(ls1))

# 地址相同

ls1 = (1,2,3)

ls2 = copy.deepcopy(ls1)

print(id(ls2))

print(id(ls1))

#外层地址不同,内层地址不同

a = [1,2,3]

b = [4,5,6]

ls1 = [a,b]

ls2 = copy.deepcopy(ls1)

print(id(ls1))

print(id(ls2))

print(id(ls1[0]))

print(id(ls2[0]))

#外层地址相同,内层地址不同

a = [1,2,3]

b = [4,5,6]

ls1 = (a,b)

ls2 = copy.deepcopy(ls1)

print(id(ls1))

print(id(ls2))

print(id(ls1[0]))

print(id(ls2[0]))

#外层地址相同,内层地址相同

a = (1,2,3)

b = (4,5,6)

ls1 = (a,b)

ls2 = copy.deepcopy(ls1)

print(id(ls1))

print(id(ls2))

print(id(ls1[0]))

print(id(ls2[0]))

#外层地址不同,内层地址相同

a = (1,2,3)

b = (4,5,6)

ls1 = [a,b]

ls2 = copy.deepcopy(ls1)

print(id(ls1))

print(id(ls2))

print(id(ls1[0]))

print(id(ls2[0]))

2. 简答

说下对生成器的理解,有几种创建方式,并用代码简单实现。

# 说下对生成器的理解,有几种创建方式,并用代码简单实现。

#一边循环一边计算的机制成为生成器generator

l = (x*2 for x in range(10))

print(l)

def fib(times):

print("开始")

n = 0

a,b = 0,1

while n < times:

yield b

a,b = b,a+b

n += 1

print("结束")

ge = fib(6)

print(ge)

print(next(ge))

print(next(ge))

print(next(ge))

def fib(times):

print("开始")

n = 0

a,b = 0,1

while n < times:

temp = yield b

print("temp = %s"%temp)

a,b = b,a+b

n += 1

print("结束")

ge = fib(6)

next(ge)

ge.send("老王")

ge.send(1)

weinxin
我的微信公众号
爱真理,得永生!          爱在灵灵久博客,网罗天下,福利大家!

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: