python中提供了很多内置函数,这些内置函数对于我们解决一些问题来说非常的方便,下面介绍一些常见的内置函数及其用法。
先看一下函数的定义:通过一个可迭代的对象返回一个枚举对象。
>>> help(enumerate) Help on class enumerate in module builtins: class enumerate(object) | enumerate(iterable[, start]) -> iterator for index, value of iterable | | Return an enumerate object. iterable must be another object that supports | iteration. The enumerate object yields pairs containing a count (from | start, which defaults to zero) and a value yielded by the iterable argument. | enumerate is useful for obtaining an indexed list: | (0, seq[0]), (1, seq[1]), (2, seq[2]), ... | | Methods defined here: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __iter__(self, /) | Implement iter(self). | | __new__(*args, **kwargs) from builtins.type | Create and return a new object. See help(type) for accurate signature. | | __next__(self, /) | Implement next(self). | | __reduce__(...) | Return state information for pickling.用法如下:
>>> li = ['a','b','c','d'] >>> list(enumerate(li)) [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')] >>> dict(enumerate(li)) {0: 'a', 1: 'b', 2: 'c', 3: 'd'}
查看函数的定义:
>>> help(eval) Help on built-in function eval in module builtins: eval(source, globals=None, locals=None, /) Evaluate the given source in the context of globals and locals. The source may be a string representing a Python expression or a code object as returned by compile(). The globals must be a dictionary and locals can be any mapping, defaulting to the current globals and locals. If only globals is given, locals defaults to it.用法:
>>> a="{'a':1}" >>> b='1*2**3' >>> eval(a) {'a': 1} >>> eval(b) 8函数的定义如下:
>>> help(exec) Help on built-in function exec in module builtins: exec(source, globals=None, locals=None, /) Execute the given source in the context of globals and locals. The source may be a string representing one or more Python statements or a code object as returned by compile(). The globals must be a dictionary and locals can be any mapping, defaulting to the current globals and locals. If only globals is given, locals defaults to it.用法:
s = ''' z = 10 su = x + y + z print(su) print('OK') ''' >>> x=1 >>> y=2 >>> exec(s) 13 OK函数的定义如下:可迭代对象是不定长参数,因此可以对多个可迭代对象进行fun的引用。
>>> help(map) Help on class map in module builtins: class map(object) | map(func, *iterables) --> map object | | Make an iterator that computes the function using arguments from | each of the iterables. Stops when the shortest iterable is exhausted. | | Methods defined here: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __iter__(self, /) | Implement iter(self). | | __new__(*args, **kwargs) from builtins.type | Create and return a new object. See help(type) for accurate signature. | | __next__(self, /) | Implement next(self). | | __reduce__(...) | Return state information for pickling.用法:
#用法1--lis int内容转换成str >>> l1=[1,2,3,4] >>> list(map(str,l1)) ['1', '2', '3', '4'] #用法2--lambda函数配合使用 >>> foo = [2, 18, 9, 22, 17, 24, 8, 12, 27] >>> list(map(lambda x: x * 2 + 10, foo)) [14, 46, 28, 54, 44, 58, 26, 34, 64]filter函数的定义吐下:
>>> help(filter) Help on class filter in module builtins: class filter(object) | filter(function or None, iterable) --> filter object | | Return an iterator yielding those items of iterable for which function(item) | is true. If function is None, return the items that are true. | | Methods defined here: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __iter__(self, /) | Implement iter(self). | | __new__(*args, **kwargs) from builtins.type | Create and return a new object. See help(type) for accurate signature. | | __next__(self, /) | Implement next(self). | | __reduce__(...) | Return state information for pickling.用法:
>>> list(filter(None,(0,0,False,11,True,1,123))) [11, True, 1, 123] >>> list(filter(lambda x:not x%2,[x for x in range(10)])) [0, 2, 4, 6, 8]函数的定义:
>>> help(zip) Help on class zip in module builtins: class zip(object) | zip(iter1 [,iter2 [...]]) --> zip object | | Return a zip object whose .__next__() method returns a tuple where | the i-th element comes from the i-th iterable argument. The .__next__() | method continues until the shortest iterable in the argument sequence | is exhausted and then it raises StopIteration. | | Methods defined here: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __iter__(self, /) | Implement iter(self). | | __new__(*args, **kwargs) from builtins.type | Create and return a new object. See help(type) for accurate signature. | | __next__(self, /) | Implement next(self). | | __reduce__(...) | Return state information for pickling.用法:
>>> l3=[1,2,3] >>> t1=('a','b','c') >>> list(zip(l3,t1)) [(1, 'a'), (2, 'b'), (3, 'c')] >>> dict(zip(l3,t1)) {1: 'a', 2: 'b', 3: 'c'} >>> str2='python' >>> list(zip((l3,t1,str2))) [([1, 2, 3],), (('a', 'b', 'c'),), ('python',)]匿名函数是不必写函数名而只实现函数体的函数,可以快速的定义函数,在高阶函数中使用可以提高代码的可读性
>>> foo = [2, 18, 9, 22, 17, 24, 8, 12, 27] >>> >>> print filter(lambda x: x % 3 == 0, foo) [18, 9, 24, 12, 27] >>> >>> print map(lambda x: x * 2 + 10, foo) [14, 46, 28, 54, 44, 58, 26, 34, 64] >>> >>> print reduce(lambda x, y: x + y, foo) 139函数使用:
再看reduce的用法。reduce把一个函数作用在一个序列[x1, x2, x3...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算,其效果就是: reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4) 比方说对一个序列求和,就可以用reduce实现: >>> def add(x, y): ... return x + y ... >>> reduce(add, [1, 3, 5, 7, 9]) 25 当然求和运算可以直接用Python内建函数sum(),没必要动用reduce。 但是如果要把序列[1, 3, 5, 7, 9]变换成整数13579,reduce就可以派上用场: >>> def fn(x, y): ... return x * 10 + y ... >>> reduce(fn, [1, 3, 5, 7, 9]) 13579 这个例子本身没多大用处,但是,如果考虑到字符串str也是一个序列,对上面的例子稍加改动,配合map(),我们就可以写出把str转换为int的函数: >>> def fn(x, y): ... return x * 10 + y ... >>> def char2num(s): ... return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s] ... >>> reduce(fn, map(char2num, '13579')) 13579#any(x)判断x对象是否有空对象,如果都为空、0、false,则返回false,如果不都为空、0、false,则返回true
#all(x)如果all(x)参数x对象的所有元素不为0、''、False或者x为空对象,则返回True,否则返回False
简单记忆:any(False)? all(True)?的布尔结果
>>> any('123') True >>> any([0,1]) True >>> any([0,'0','']) True >>> any([0,'']) False >>> any([0,'','false']) True >>> any([0,'',bool('false')]) True >>> any([0,'',False]) False >>> any(('a','b','c')) True >>> any(('a','b','')) True >>> any((0,False,'')) False >>> any([]) False >>> any(()) False >>> all(['a', 'b', 'c', 'd']) #列表list, True >>> all(['a', 'b', 'c', 'd']) #列表list,元素都不为空或0 True >>> all(['a', 'b', '', 'd']) #列表list,存在一个为空的元素 False >>> all([0, 1,2, 3]) #列表list,存在一个为0的元素 False >>> all(('a', 'b', 'c', 'd')) #元组tuple,元素都不为空或0 True >>> all(('a', 'b', '', 'd')) #元组tuple,存在一个为空的元素 False >>> all((0, 1,2, 3)) #元组tuple,存在一个为0的元素 False >>> all([]) # 空列表 True >>> all(()) # 空元组 True >>> #注意:空元组、空列表返回值为True,这里要特别注意 >>> all(('', '', '', '')) #元组tuple,全部为空的元素 False >>> all('') True >>> #如果all(x)参数x对象的所有元素不为0、''、False或者x为空对象,则返回True,否则返回False >>>
常见内置函数的使用熟记即可,即使有面试题也是简单的函数使用,因此了解函数的用法就行
转载于:https://www.cnblogs.com/forfreewill/articles/9305159.html