首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Python3中内置函数

1:查看内置函数及函数说明

Python3中有哪些内置函数呢?可以使用下面代码查看:

print([item for item in dir(__builtins__) if not item.startswith('__') and item[0].islower() ]) """结果:['abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']"""

如果不知道某个函数怎么用,怎么办?使用help函数查看:

print(help(abs))'''abs(x, /) Return the absolute value of the argument.''' print(help(all))'''all(iterable, /) Return True if bool(x) is True for all values x in the iterable. If the iterable is empty, return True.''' print(help(any))'''any(iterable, /) Return True if bool(x) is True for any x in the iterable. If the iterable is empty, return False.'''

2:内置函数

2.1 map

print(help(map)) '''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. ......'''

意思就是把后面可迭代对象中每个元素传递给func处理:

lst1 = [1,2,3]lst2 = [4,5,6] # 一个参数,对应后面一个可以迭代对象ret = list(map(lambda x: x **2,lst1))print(ret) # [1, 4, 9] # 两个参数,对应后面两个可以迭代对象ret = list(map(lambda x,y:x+y + 10,lst1,lst2))print(ret) # [15, 17, 19]

2.2 filter

print(help(filter))'''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. ......'''

对后面可迭代对象中的每个元素,调用前面的函数处理,如果处理结果为True,那么这个元素会保留下来,否则会被过滤掉;如果前面函数传递是None,那么会把可迭代对象中为真的值保留下来。

lst1 = [0,1,2,3,4,5,6,7,8,9] def f(x): return x % 3 == 0 # 使用普通函数 ret = list(filter(f,lst1))print(ret) # [0, 3, 6, 9] # 使用匿名函数ret = list(filter(lambda x:x % 3 == 0,lst1))print(ret) # [0, 3, 6, 9] lst2 = [0,4,None,5,6,{},[1,2,3,0]]ret = list(filter(None,lst2))print(ret) # [4, 5, 6, [1, 2, 3, 0]] 只是作用于顶层元素

2.3 zip

print(help(zip)) """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. ...... | """

示例:

lst1 = [1,2,3]lst2 = [4,5,6,14]lst3 = [7,8,9,17,18]z = zip(lst1,lst2,lst3)print(list(z)) # 输出: [(1, 4, 7), (2, 5, 8), (3, 6, 9)] # 自己实现的zipdef myzip(*seqs): seqs = [list(s) for s in seqs] res = [] while all(seqs): res.append( tuple(s.pop(0) for s in seqs )) return reslst1 = [1,2,3]lst2 = [4,5,6,14]lst3 = [7,8,9,17,18]z = myzip(lst1,lst2,lst3) print(list(z)) # [(1, 4, 7), (2, 5, 8), (3, 6, 9)]

2.4 sorted 排序

print(help(sorted)) """sorted(iterable, /, *, key=None, reverse=False) Return a new list containing all items from the iterable in ascending order. A custom key function can be supplied to customize the sort order, and the reverse flag can be set to request the result in descending order."""

参数说明:

iterable:是可迭代类型;

key:传入一个函数名,函数的参数是可迭代类型中的每一项,根据函数的返回值大小排序;

reverse:排序规则. reverse = True  降序 或者 reverse = False 升序,有默认值。

返回值:有序列表

lst = [3,1,44,5,11,90]print(lst) # 降序lst2= sorted(lst,reverse = True)print(lst2) # [90, 44, 11, 5, 3, 1] # 升序(默认的) lst2= sorted(lst)print(lst2) # [1, 3, 5, 11, 44, 90] lst = [3,1,44,-5,11,-90]# 按照元素的绝对值来排序,降序lst2= sorted(lst,key=abs,reverse = True)print(lst2) # [-90, 44, 11, -5, 3, 1] lst = [3,1,44,-5,11,-90]# 使用匿名函数,降序lst2= sorted(lst,key=lambda x:x if x >= 0 else -x,reverse = True)print(lst2) # [-90, 44, 11, -5, 3, 1]

  • 发表于:
  • 原文链接https://kuaibao.qq.com/s/20200804A04P8P00?refer=cp_1026
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券