多一句没有,少一句不行,用最短的时间,教会你有用的技术。
最近在阅读 《python官方文档》, 好多用法自己都不知道,更可惜的是很多用法还很常用,特别是刷过算法的你。
今天先讲几个特别常见的内置函数,记得之前面试的时候还被问map和reduce的区别。
哈哈,那个时候还是刚学python,不停刷着百度寻找答案,死记硬背。时间长了,就忘记了,今天就让我们好好的学习下,别人再问到的时候就能自己说上一二三了。
Built-in Functions
✅ python 内置函数

map() 函数
✅ 语法:
map(func, *iterables) --> map objectMake an iterator that computes the function using arguments fromeach of the iterables. Stops when the shortest iterable is exhausted.

✅ 解释:
创建一个迭代器,对传入的参数进行计算.返回值是一个迭代器。 翻译的有点直白,大家莫见怪哈.
✅示例:
单个
from numpy import squaremap_test = [1, 2, 3, 4, 5, 6]print(list(map(square, map_test)))# [1, 4, 9, 16, 25, 36]
filter() 函数
✅ 语法:
filter(function or None, iterable) --> filter objectReturn an iterator yielding those items of iterable for which function(item)is true. If function is None, return the items that are true.

✅ 解释:
通过字面意思能够看出来它是过滤用的.filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表。
✅示例:
from numpy import squarefilter_test = [1, 2, 3, 4, 5, 6]print(list(filter(square, filter_test)))# [1, 2, 3, 4, 5, 6]print("================")filter_test2 = [1, 2, 3, 4, 5, 6]print(list(filter(None,filter_test2)))print("================")def function_filter(num):if num%2==0:return numfilter_test2 = [1, 2, 3, 4, 5, 6]print(list(filter(function_filter,filter_test2)))# [1, 2, 3, 4, 5, 6]# ================# [1, 2, 3, 4, 5, 6]# ================# [2, 4, 6]

reduce() 函数
这个函数在python3已经不是内置函数了,需要从 functools 模块来调用 reduce() 函数.
✅ 语法:
reduce(function, sequence[, initial]) -> valueApply a function of two arguments cumulatively to the items of a sequence,from left to right, so as to reduce the sequence to a single value.For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates((((1+2)+3)+4)+5). If initial is present, it is placed before the itemsof the sequence in the calculation, and serves as a default when thesequence is empty.

✅ 解释:
reduce() 函数会对参数序列中元素进行累积。用传给 reduce 中的函数 function(有两个参数)先对集合中的第 1、2 个元素进行操作,得到的结果再与第三个数据用function 函数运算,最后得到一个结果。
✅ 示例:
from functools import reducedef reduce_test(x,y):return x+yprint(reduce(reduce_test, [1, 2, 3, 4, 5]))# 15print(reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]))# 15
zip()函数
这个用的很多.
✅ 语法:

✅ 解释:
zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。
✅ 示例:
print(list(zip(range(5), range(1, 20, 2))))# [(0, 1), (1, 3), (2, 5), (3, 7), (4, 9)]
后记
为了便于大家学习,我把链接放在这里,方便随时复习查看.
✅ python2内置函数
https://www.runoob.com/python/python-built-in-functions.html

✅ python3内置函数
https://www.runoob.com/python3/python3-built-in-functions.html

