Python learning small record 1

zip

#input
a = [1,2,3]
b = [4,5,6]
zip(a,b)#这里的返回值是一个object
print(list(zip(a,b)))#将转换为list
#output
[(1,4),(2,5),(3,6)]

lambda

Generally speaking, we define a function as follows:

#input
def fun1(x.y):
	return(x+y)

If you use lambda, it can be written as follows:

#input
fun2 = lambda x,y:x+y #把两行的代码变成一行,可以用于定义一些简单的方程

map

Take the above function fun1 as an example

#input
print(list(map(fun1,[1],[2])))
#output
[3]
#input
print(list(map(fun2,[1,3],[2,5])))
#output
[3,8]

Shallow copy and deep copy

Reference copy

Usually when we write code:

a = [1,2,3]	#创建列表a
b = a			#创建列b将a赋值给b,那么现在 a和b同时指向内存中的一块区域
print(id(a)==id(b))
#output
True
a[1] = 444
print(a)
#output
[1,444,3]
print(b)
#output
[1,444,3]

If you just copy the reference alone, then the two variables will eventually point to the same area

Shallow copy

import  copy
a = [1,3,6]
 b = copy.copy(a)
 print(id(a)==id(b))
 #output
 False
 a[1] = 777
 print(a)
 print(b)
 #output
 [1,777,6]
 [1,3,6]
#可以看出使用浅复制会从新开辟一个区域使得a,b不再指向同一个区域

However, shallow copy can only copy the first level list. For nested lists, shallow copy cannot do anything.

import copy
a = [1,555,[8,59,5]]
b = copy.copy(a)
print(id(a[2])==id(b[2]))
#output
True

##Deep copy
Let's try deep copy, the code is as follows:

import copy
a = [1,555,[8,59,5]]
b = copy.deepcopy(a)
print(id(a[2])==id(b[2]))
#output
False

Guess you like

Origin blog.csdn.net/gujiguji_c/article/details/107207437