day5_深拷贝和浅拷贝的区别、三元运算符、列表生成式
深拷贝和浅拷贝的区别:
浅拷贝指向同一块内存地址,深拷贝是开辟了另外一个内存地址,但是内存地址变了不一定是深拷贝
import copy
a = ['123', ['aaa', 'bbb']]
b = copy.deepcopy(a) # 深拷贝是重新开辟了一块内容空间,a和b地址不一样了
c = a[:] # 浅拷贝
d = a # 浅拷贝
e = a.copy() # 浅拷贝
f = copy.copy(a) # 浅拷贝
a[-1].append('99')
print(a, b) # 打印出['123',['aaa','bbb',99]] ['123',['aaa','bbb']]
a = b = c = ['123', 'aaa']
c.append('red')
print(a, b, c)会打印出['123','aaa','red'] ['123','aaa','red'] ['123','aaa','red']
a = b = c = 'red12'
c = 'hello'
print(a, b, c)会打印出red12 red12 hello
a = b = c = ('green', 'blue')
c = ('black', 'white')
print(a, b, c)会打印出('green', 'blue') ('green', 'blue') ('black', 'white')
# 字符串和元组都是不可变的,和list的内存地址不一样
import copy
a = {1: 'one', 2: 'two', 3: 'three'}
b = a.copy() # 全拷贝
c = a # 赋值
d = copy.copy(a) # 浅拷贝
# 打印结果都是一样的,但是b全拷贝只是把列表内容拷过去了,地址b和a,c的地址不一样,id(a)和id(c)一样
print(a, b, c, d)
print(id(a))
print(id(b))
print(id(c))
print(id(d)) # 地址d和a、b、c的都不一样
dic = {'1': 1, '2': 2}
c = dic.copy() # c全拷贝只是把字典内容拷过去了,地址c和dic不一样,指向不同的内存地址
dic['1'] = 5
su = dic['1'] + c['1']
print(su) # 打印6
三元运算符:
a = 5
b = 4
c = a if a > b else b
print(c)
列表生成式,也叫列表推导式,可以是一个list,打印一个list,也可以是set,打印生成一个set,也可以使用元组,但是要加list,即print(list(res))实现结果,打印生成一个list
res = [i for i in range(1, 100) if i % 2 != 0]
print(res)
res = (i for i in range(1, 100) if i % 2 != 0)
print(list(res))
res = {i for i in range(1, 100) if i % 2 != 0}
print(res)
list1 = [(x, y) for x in range(5) for y in range(5) if x % 2 == 0 and y % 2 != 0]
print(list1) # 打印出[(0, 1), (0, 3), (2, 1), (2, 3), (4, 1), (4, 3)]