zoukankan      html  css  js  c++  java
  • 编程方法论与三个重要函数

    1.方法论:面向对象编程

         面向过程编程:将一个大步骤分解为许多个小步骤,一步一步解决

         函数式编程:数学式与编程式,强调简洁性,一步解决 

     1 #面向对象:
     2 def test(x):
     3     a = x+1
     4     b = a**2
     5     return b
     6 print(test(10))
     7 #函数式编程:
     8 def test(x):
     9     return (x+1)**2
    10 print(test(10))

    2.map()函数:对输入迭代对象逐一进行操作在生成迭代器 

     1 list_1 = [1,23,134,111]
     2 def test_1(x):
     3     x**=2
     4     return x
     5 def test(func,array):
     6     new_list=[]
     7     for item in array:
     8         a = func(item)
     9         new_list.append(a)
    10     return new_list
    11 print(test(test_1,list_1))
    12 print(test(lambda x:x**2,list_1))
    13 (print(list(map(lambda x:x**2,list_1))) #三个打印结果一样
     1 list_2 = ['a','b','c','d']
     2 def test_2(x):
     3     x = x+'_sb'
     4     return x
     5 def test(func,array):
     6     new_list = []
     7     for item in array:
     8         new_list.append(func(item))
     9     return new_list
    10 print(test(test_2,list_2))
    11 print(test(lambda x:x+'_sb',list_2))
    12print(list(map(lambda x:x+'_sb',list_2)))

    3.filter()函数:通过布尔值的判断来确定过滤出的可迭代对象中的元素(True时打印出)

    1 list_3 = ['Mr.Li','Mrs.Wang','Mr.Liu','Mrs.Zhang']
    2 filter(lambda x:not x.startswith('Mrs'),list_3) #<filter object at 0x00000000026B63C8> 表示为迭代器,需要用列表来表示出来
    3 print(filter(lambda x:not x.startswith('Mrs'),list_3)) #无打印结果
    4 print(list(filter(lambda x:not x.startswith('Mrs'),list_3)))#正常结果

    4.reduce()函数:对所输入可迭代对象进行合并

    1 from functools import reduce #需要从模块中导入函数
    2 list_4 = [12,11,10]
    3 print(reduce(lambda x,y:x+y,list_4))
    4 print(reduce(lambda x,y:x+y,list_4,100)) #第三个参数可以自己设定,为加入计算的初始值
  • 相关阅读:
    秦腾与教学评估【前缀和+二分】
    c++中成员函数声明时const得作用
    分形【递归】
    飞行兄弟【二进制枚举+异或】
    爬取4k图片网图片
    爬虫爬取博客园文章的文字【练手】
    【YBTOJ】求 f 函数
    【YBTOJ】划分数列
    【学习笔记】高斯消元法
    【Luogu P4588】 [TJOI2018]数学计算
  • 原文地址:https://www.cnblogs.com/lzjdsg/p/10162730.html
Copyright © 2011-2022 走看看