0.请编写用例并加以说明,解释Python中赋值拷贝、深拷贝与浅拷贝的区别
赋值拷贝:
#赋值拷贝: 直接赋值
# 就是两个变量同时指向同一个地址,
# 原列表,被赋值的也会改变,只是多个一个引用的对象
源代码:
a = [10,[5,6],6]
b = a
print(id(a),id(b))
a.append(7)
print(a,b)
print(id(a),id(b))
运行结果:
1614393729672 1614393729672
[10, [5, 6], 6, 7] [10, [5, 6], 6, 7]
1614393729672 1614393729672
浅拷贝:
#浅拷贝
#变量指向地址会变,不会跟随赋值对象的改变而改变
#但是会跟着原对象的子类的的改变而改变
源代码:
import copy
c = [5,[3,8],9]
d = copy.copy(c) #copy浅拷贝
print(id(c),id(d))
c.append(6) #父类中加一个6,不改变
print(c,d)
c[1].append(7) #z子类中添加一个7,改变
print(c,d)
运行结果:
1614395776136 1614395774920
[5, [3, 8], 9, 6] [5, [3, 8], 9]
[5, [3, 8, 7], 9, 6] [5, [3, 8, 7], 9]
深拷贝:
#深拷贝
# 比浅拷贝的程度更深
# 意思就是不会因为原来拷贝的对象任何修改而做出任何改变
源代码:
import copy
e = [1,[5,2],3]
f = copy.deepcopy(e) #copy深拷贝
print(id(e),id(f))
e.append(4) #父类中加一个4,不改变
print(e,f)
e[1].append(8) #子类中添加一个8,不改变
print(e,f)
运行结果:
1614395899848 1614395899528
[1, [5, 2], 3, 4] [1, [5, 2], 3]
[1, [5, 2, 8], 3, 4] [1, [5, 2], 3]
1.编写函数实现指定个数的元素翻转到数组的尾部。
#例如:arr = [1,2,3,4,5,6] 将长度为 6 的 数组 arr 的前面 2 个元素翻转到数组尾部。
#得到: arr = [3,4,5,6,1,2]
源代码:
def change(a,n):
for i in range(n):
a.append(a[i])
while n:
del a[0]
n = n-1
arr = [1,2,3,4,5,6]
change(arr,2)
print(arr)
运行结果:
D:\PyCharmProject\venv\Scripts\python.exe D:/PyCharmProject/Test2/1.py
[3, 4, 5, 6, 1, 2]
Process finished with exit code 0
2.编写程序实现给定一个字符串,然后判断指定的子字符串是否存在于该字符串中。
源代码:
string1 = "I am a good student"
if "am" in string1:
print("am在字符串中")
else:
print("am不在字符串中")
if "bad" in string1:
print("bad在字符串中")
else:
print("bad不在字符串中")
运行结果:
D:\PyCharmProject\venv\Scripts\python.exe D:/PyCharmProject/Test2/2.py
am在字符串中
bad不在字符串中
Process finished with exit code 0
3.编写程序实现给定一个字典,计算所有键值为数字值的乘积。
源代码:
#判断值是否为数字
def type(d):
if isinstance(d,int):
return 1
else:
return 0
dict_dictionary = {"asd":123,"sad":"adsa","fdf":15}
sum = 1
for key in dict_dictionary:
if (type(dict_dictionary[key])) == 1:
sum = sum * dict_dictionary[key]
else:
continue
print(sum)
运行结果:
D:\PyCharmProject\venv\Scripts\python.exe D:/PyCharmProject/Test2/3.py
1845
Process finished with exit code 0
4.简单大乐透小游戏不用random.sample函数
# 编写函数实现大乐透
# 前五个数字互不重复从1-35中挑选
# 后2个数字互不重复从1-12中挑选
# 前5个数字和后2个数字可以重复
源代码:
import random
l1 = []
l2 = []
def Happy():
for i in range(99):
x = random.choice(range(1,36))
try:
l1.index(x)
continue
except:
l1.append(x)
if len(l1) == 5:
break;
for i in range(99):
y = random.choice(range(1,13))
try:
l2.index(y)
continue
except:
l2.append(y)
if len(l2) == 2:
break
return l1+l2
print(Happy())
运行结果:
D:\PyCharmProject\venv\Scripts\python.exe D:/PyCharmProject/Test2/大乐透.py
[25, 17, 26, 6, 8, 4, 8]
Process finished with exit code 0