内建函数

filter

filter(function, iterable) 函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表。

  • function 判断函数
  • iterable 可迭代对象 ```python def filter_func(): oldlist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] newlist1 = list(filter(isEvenNum, oldlist)) print(“过滤出奇数:”, newlist1) newlist2 = list(filter(lambda x: x % 2 == 0, oldlist)) print(“过滤出偶数:”, newlist2)

获取基数

def isEvenNum(n): return n % 2 == 1

  1. <a name="ZP3UQ"></a>
  2. ### map
  3. > map(function, iterable, ...) 会根据提供的函数对指定序列做映射
  4. - function 函数
  5. - iterable 一个或多个序列
  6. ```python
  7. def map_func():
  8. oldlist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  9. newlist1 = list(map(lambda x: x * 2, oldlist))
  10. print("旧数组里的数 * 2 = ", newlist1)
  11. newlist2 = list(map(lambda x, y: x + 2, oldlist, newlist1))
  12. print("oldlist 与 newlist2 相加等于", newlist2)

reduce

reduce(function, iterable[, initializer]) 函数会对参数序列中元素进行累积。 注意要引入:from functools import reduce

  • function 函数,有两个参数
  • iterable 可迭代对象
  • initializer 可选,初始参数
    1. def reduce_func():
    2. res = reduce(lambda x, y: x + y, [2, 3, 4], 1)
    3. print("累加等于:", res)

zip

zip([iterable, …]) 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表

  • iterabl 一个或多个迭代器
    1. # zip 合并函数
    2. def zip_func():
    3. for i in zip((1, 2, 3), (4, 5, 6), (7, 8, 9)):
    4. print(i)
    5. dict1 = {"a": "aa", "b": "bb", "c": "cc"}
    6. dict2 = dict(zip(dict1.values(), dict1.keys()))
    7. print("key 与 value 对调:", dict2)

闭包

在函数中可以(嵌套)定义另一个函数时,如果内部的函数引用了外部的函数的变量,则可称为闭包

  1. def add_func1(num1, num2):
  2. return num1 + num2
  3. # 闭包函数
  4. def add_func2(num1):
  5. def add(num2):
  6. return num1 + num2
  7. return add
  8. # 计算器, 这里用列表是
  9. def counter_func(num1 = 0):
  10. cnt = [num1]
  11. def add_one():
  12. cnt[0] += 1
  13. return cnt[0]
  14. return add_one
  15. def closure_func():
  16. re1 = add_func1(1, 2)
  17. print("re1 类型", type(re1), re1)
  18. re2 = add_func2(1)
  19. print("re2 类型", type(re2), re2(2))
  20. num1 = counter_func(5)
  21. print(num1())
  22. print(num1())
  23. print(num1())

参考