课后作业
num1 = [1,2,3,4]
num2 = [4,5,6,7]
num3 = [9,4,5,7]
#用第一版本:不要用到函数 列表里每个元素 加减乘除
加法
ret1 = []
for i in num1:
ret1.append(i+1)
print(ret1)
ret2 = []
for i in num2:
ret2.append(i+1)
print(ret2)
ret3 = []
for i in num3:
ret3.append(i+1)
print(ret3)
减法
ret1 = []
for i in num1:
ret1.append(i-1)
print(ret1)
ret2 = []
for i in num2:
ret2.append(i-1)
print(ret2)
ret3 = []
for i in num3:
ret3.append(i-1)
print(ret3)
乘法
ret1 = []
for i in num1:
ret1.append(i*3)
print(ret1)
ret2 = []
for i in num2:
ret2.append(i*3)
print(ret2)
ret3 = []
for i in num3:
ret3.append(i*3)
print(ret3)
除法
ret1 = []
for i in num1:
ret1.append(i/2)
print(ret1)
ret2 = []
for i in num2:
ret2.append(i/2)
print(ret2)
ret3 = []
for i in num3:
ret3.append(i/2)
print(ret3)
#用第二版本:函数做 列表里每个元素 加减乘除
加法
def map_test(array):
ret=[]
for i in num1:
ret.append(i+2)
return ret
ret1=map_test(num1)
ret2=map_test(num2)
ret3=map_test(num3)
print(ret1)
print(ret2)
print(ret3)
减法
def map_test2(array):
ret=[]
for i in num1:
ret.append(i-2)
return ret
ret1=map_test2(num1)
ret2=map_test2(num2)
ret3=map_test2(num3)
print(ret1)
print(ret2)
print(ret3)
乘法
def map_test3(array):
ret=[]
for i in num1:
ret.append(i*2)
return ret
ret1=map_test3(num1)
ret2=map_test3(num2)
ret3=map_test3(num3)
print(ret1)
print(ret2)
print(ret3)
除法
def map_test4(array):
ret=[]
for i in num1:
ret.append(i/2)
return ret
ret1=map_test4(num1)
ret2=map_test4(num2)
ret3=map_test4(num3)
print(ret1)
print(ret2)
print(ret3)
#用第三个版本:用到函数,函数第一个参数是函数,第二个参数是我们num1,num2,num3
def add_one(x):
return x+1
def reduce_one(x):
return x-1
def chengfa_one(x):
return x*2
def chufa_one(x):
return x/2
def map_test(func,array)
ret = []
for i in num1:
res = func(i)
ret.append(res)
return ret
print(map_test(add_one,num1))#加法
print(map_test(add_one,num2))
print(map_test(add_one,num3))
print(map_test(reduce_one,num1))#减法
print(map_test(reduce_one,num2))
print(map_test(reduce_one,num3))
print(map_test(chengfa_one,num1))#乘法
print(map_test(chengfa_one,num2))
print(map_test(chengfa_one,num3))
print(map_test(chufa_one,num1))#除法
print(map_test(chufa_one,num2))
print(map_test(chufa_one,num3))
#用第四个版本:直接用map()函数去完成
print(list(map(lambda x : x+1,num1)))
print(list(map(lambda x : x+1,num2)))
print(list(map(lambda x : x+1,num3)))
print(list(map(lambda x : x-1,num1)))
print(list(map(lambda x : x-1,num2)))
print(list(map(lambda x : x-1,num3)))
print(list(map(lambda x : x*2,num1)))
print(list(map(lambda x : x*2,num2)))
print(list(map(lambda x : x*2,num3)))
print(list(map(lambda x : x/2,num1)))
print(list(map(lambda x : x/2,num2)))
print(list(map(lambda x : x/2,num3)))