一.深浅拷贝
1.浅拷贝
对于浅copy来说,第一层创建的是新的内存地址,而从第二层开始指向的都是同一个内存地址,所以,对于第二层以及更深层的层数来说,保持一致性
from copy import copy,deepcopy
a = [1,2,3,4,5,['hello',' world']]
b = copy(a)
a[2]='nihao'
print(a,b) #[1,2,'nihao',4,5,['hello world']] [1,2,3,4,5,['hello world']]
a[5][0]='你好'
print(a,b) #[1, 2, 'nihao', 4, 5, ['你好', ' world']] [1, 2, 3, 4, 5, ['你好', ' world']]
2.深拷贝
对于深copy来说,两个是完全独立的,改变任意一个任何元素(无论多少层),另一个也绝不会改变
from copy import copy,deepcopy
a = [1,2,3,4,5,['hello',' world']]
b = deepcopy(a)
a[2]='nihao'
print(a,b) #[1, 2, 'nihao', 4, 5, ['hello', ' world']] [1, 2, 3, 4, 5, ['hello','world']]
a[5][0]='你好'
print(a,b) #[1, 2, 'nihao', 4, 5, ['你好', ' world']] [1, 2, 3, 4, 5, ['hello', 'world']]
二.函数
1.函数的返回值return
结束函数,后面的代码统统不执行,只能在函数中用
函数可以返回多个值,是以元组的形式返回。
def hello():
return 1,222,47,
print(hello()) #(1, 222, 47)
2.函数的参数
函数定义时的参数是形参,函数调用时的参数是实参。函数的形参大于实参。
def new_len(a): # 定义函数时:参数:形参。
count = 0
for i in a:
count += 1
return count
l1 = [1, 2, 3]
print(new_len(l1)) # 函数的调用者:参数 实参。
3.不定长函数
def hello(*args):
print(args)
hello(5,2,1,6,3) #(5, 2, 1, 6, 3)
def hello(**kwargs):
print(kwargs)
hello(nihao='谢谢',byebye = "再见") #{'nihao': '谢谢', 'byebye': '再见'}
#求最大值
def get_max(*args):
max = args[0]
for i in args[1:]:
if max<i:
max = i
return max
print(get_max(5,3,2,7,1,7,3,555,4))
4.递归函数
def age(n):
if n == 1:
return 18
else:
return age(n - 1) + 2
print(age(4)) #24
def get_num(n):
if n==1:
return n
return n+get_num(n-1)
print(get_num(100)) #5050
四.斐波那契数列
def get_data(num):
x = 0
y = 1
for i in range(num):
x,y = y,x+y
yield x
for i in get_data(10):
print(i)
五.装饰器
import time
def get_data(func):
def get_hello(*args,**kwargs):
begin_time = time.time()
data = func()
stop_time = time.time()
print(stop_time - begin_time)
return data
return get_hello
@get_data
def hello():
time.sleep(3)
print(12345)
return 'ok'
print(hello())
可迭代对象
1.能被for循环遍历的元素
lists = [1,2,3,4]
for i in lists:
print(i)
迭代器
内部含有'__iter__'并且'__next__'方法能调用,就是迭代器
生成器
1.生成器表达式
a = (i for i in range(1, 11))
print(a) # <generator object <genexpr> at 0x0000017A8F07FED0>
print(next(a)) # 1
print(next(a)) # 2
print(next(a)) # 3