个人感受:函数式编程,就是将数据,输入管道中,得到输出结果。并且,输入不变,则输出也不变。
=======
星星之火,可以燎原
HEAD
个人感受:函数式编程,就是将数据,输入管道中,得到输出结果。并且,输入不变,则输出也不变。
>>>>>>> 4ef99384a791603d1ae54a12162221aa23eb330e函数式编程与一般编程的区别:
测试例程①
需求说明:对于数据data = [1,2,3,4,5],要求输出data = [2,4,6,8,10]
data = [1, 2, 3, 4, 5, 6]
# 方法1:循环添加
res1 = []
for n in data:
res1.append(n * 2)
print(res1)
# 方法2:列表表达式
res2 = [n * 2 for n in data]
print(res2)
# 方法3:函数式编程
# 第一步:创建管道函数
def func(i):
return i * 2
# 第二步:将数据输入管道
res3 = map(func, data)
res3 = list(res3)
print(res3)
点评:从三种方法的对比可以发现,函数式编程的优点,就是在保证对单个数据的处理不出错的情况下,对多个数据的处理也能不出错。
测试例程②
需求说明:将摄氏温度,转变为华氏温度:摄氏温度*9/5+32
data = [
{"city": "Beijing", "temp": 20.8},
{"city": "Changsha", "temp": 22.4},
{"city": "Chongqing", "temp": 22.8},
{"city": "Guangzhou", "temp": 25.1},
{"city": "Shanghai", "temp": 20.3},
{"city": "HongKong", "temp": 25.9}]
# # 方法1:循环添加
res1 = []
for item in data:
# 复制字典,避免在原字典上修改
new_item = item.copy()
new_item['temp'] = item['temp'] * 9 / 5 + 32
res1.append(new_item)
for item in res1:
print(item)
# 方法2:列表表达式
def c_to_f(t):
new_t = t.copy()
new_t['temp'] = t['temp'] * 9 / 5 + 32
return new_t
res2 = [c_to_f(n) for n in data]
for item in res2:
print(item)
# 方法3:函数式编程
# 第一步:创建管道函数
def c_to_f(t):
new_t = t.copy()
new_t['temp'] = t['temp'] * 9 / 5 + 32
return new_t
# 第二步:将数据输入管道
res3 = map(c_to_f, data)
res3 = list(res3)
for item in res3:
print(item)
点评:理解函数式编程后,寻找bug的时候会方便很多
<<<<<<< HEAD