{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 4.7 内置函数"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 官方文档\n",
"https://docs.python.org/3/library/functions.html"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Python 3.12内置了71个函数可以直接使用,这些函数如下表所示,其具体语法可以参考官方文档https://docs.python.org/3/library/functions.html"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"| | | | | | |\n",
"|:----|:----|:----|:----|:----|:----|\n",
"| <font color=Red>__A__</font> | <font color=Red>__D__</font> | <font color=Red>__H__</font> | <font color=Red>__M__</font> | <font color=Red>__R__</font> | <font color=Red>__T__</font> |\n",
"| abs() | delattr() | hasattr() | map() | range() | tuple() |\n",
"| aiter() | dict() | hash() | max() | repr() | type() |\n",
"| all() | dir() | help() | memoryview() | reversed() | |\n",
"| any() | divmod() | hex() | min() | round() | <font color=Red>__V__</font> |\n",
"| anext() | | | | | vars() |\n",
"| ascii() | <font color=Red>__E__</font> | <font color=Red>__I__</font> | <font color=Red>__N__</font> | <font color=Red>__S__</font> | |\n",
"| | enumerate() | id() | next() | set() | <font color=Red>__Z__</font> |\n",
"| <font color=Red>__B__</font> | eval() | input() | | setattr() | zip() |\n",
"| bin() | exec() | int() | <font color=Red>__O__</font> | slice() | |\n",
"| bool() | | isinstance() | object() | sorted() | <font color=Red>_____</font> |\n",
"| breakpoint() | <font color=Red>__F__</font> | issubclass() | oct() | staticmethod() | __import__() |\n",
"| bytearray() | filter() | iter() | open() | str() | |\n",
"| bytes() | float() | | ord() | sum() | |\n",
"| | format() | <font color=Red>__L__</font> | | super() | |\n",
"| <font color=Red>__C__</font> | frozenset() | len() | <font color=Red>__P__</font> | | |\n",
"| callable() | | list() | pow() | | |\n",
"| chr() | <font color=Red>__G__</font> | locals() | print() | | |\n",
"| classmethod() | getattr() | | property() | | |\n",
"| compile() | globals() | | | | |\n",
"| complex() |\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"| 函数 | 说明 | \n",
"|:----|:----|\n",
"| <font color=Red>bin</font> | 把一个整数转换成以'0b'开头的二进制字符串,例如:bin(123)会返回'0b1111011'。 |\n",
"| <font color=Red>hex</font> | 将一个整数转换成以'0x'开头的十六进制字符串,例如:hex(123)会返回'0x7b'。 |\n",
"| <font color=Red>oct</font> | 把一个整数转换成以'0o'开头的八进制字符串,例如:oct(123)会返回'0o173'。| \n",
"| <font color=Red>input</font> | 从输入中读取一行,返回读到的字符串。| \n",
"| <font color=Red>print</font> | 打印输出。| \n",
"| <font color=Red>len</font> | 获取字符串、列表等的长度。 |\n",
"| <font color=Red>max</font> | 返回多个参数或一个可迭代对象中的最大值,例如:max(12, 95, 37)会返回95。| \n",
"| <font color=Red>min</font> | 返回多个参数或一个可迭代对象中的最小值,例如:min(12, 95, 37)会返回12。 |\n",
"| <font color=Red>chr</font> | 将Unicode编码转换成对应的字符,例如:chr(8364)会返回'€'。| \n",
"| <font color=Red>ord</font> | 将字符转换成对应的Unicode编码,例如:ord('€')会返回8364。| \n",
"| <font color=Red>abs</font> | 返回一个数的绝对值,例如:abs(-1.3)会返回1.3| \n",
"| <font color=Red>pow</font> | 求幂运算,例如:pow(2, 3)会返回8;pow(2, 0.5)会返回1.4142135623730951。 |\n",
"| <font color=Red>sum</font> | 对一个序列中的项从左到右进行求和运算,例如:sum(range(1, 101))会返回5050。 |\n",
"| <font color=Red>round</font> | 按照指定的精度对数值进行四舍五入,例如:round(1.23456, 4)会返回1.2346。| \n",
"| <font color=Red>range</font> | 构造一个范围序列,例如:range(100)会产生0到99的整数序列。 |\n",
"| <font color=Red>type</font> | 返回对象的类型,例如:type(10)会返回int;而type('hello')会返回str。 |\n",
"| <font color=Red>open</font> | 打开一个文件并返回文件对象。 |"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"这些函数中的大部分会在本书的各章节出现,这里只介绍几个常用函数:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## help( [object] )"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"help()可返回方括号中对象的帮助信息,参数是一个字符串,可以是模块名、函数名、类名、方法名、关键字或文档主题。当参数省略时,进入帮助环境,再输入要查找的对象名,返回该对象的帮助。例如,查看函数id的帮助信息:"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"help( id )"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"或者省略参数直接使用help()进入帮助环境,再输入要帮助的对象,如 id 。"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [],
"source": [
"help() #进入帮助环境后再输入要查看的对象"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## id( object )"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"id()函数返回括号中对象的<font color=Red>__内存地址__</font>(identity),一个对象的id值在CPython解释器(官方解释器)里就代表它在内存中的地址。\n",
"\n",
"id值是一个整数,并且在对象的生命周期内唯一且保持不变,在不重合的生命周期里,两个不同的对象可能会出现相同的id值。\n",
"\n",
"对于字符串、整数等类型,变量的id是<font color=Red>__随着值的改变而改变__</font>的。用<font color=Red>__is__</font>运算符判断两个对象是否相同时,依据就是这个id值是否相同。"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"print( id(100) ) # 100是整数对象,输出其地址\n",
"n = 100 # 赋值,即在100这个整数对象上加上n这个引用\n",
"print(id(n)) # 输出n的id,即是整数100的id\n",
"m = 100 # 赋值,即在100这个整数对象上加上m这个引用\n",
"print(id(m)) # 输出m的id,即是整数100的id\n",
"print(m is n) # m和n的id一样,True"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## type(object)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"type()函数查看数据的类型,其返回值是要查询的对象的类型信息。"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"print( type(1), type('1'), type([1,2,3]) ) # <class 'int'> <class 'str'> <class 'list'> \n",
"print( type(range(5)) ) # <class 'range'> "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"函数是对功能相对独立且会重复使用的代码的封装。学会使用定义和使用函数,就能够写出更为优质的代码。 \n",
"当然,Python 语言的标准库中已经为我们提供了大量的模块和常用的函数,用好这些模块和函数就能够用更少的代码做更多的事情;如果这些模块和函数不能满足我们的要求,可能就需要自定义函数,然后再通过模块来管理这些自定义函数。"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## bin(x):将一个整数转换为带前缀 \"0b\" 的二进制数字符串\n",
"## hex(x):将整数转换为带前缀 \"0x\" 前缀的小写十六进制数字符串。\n",
"## oct(x):将整数转换为带前缀 \"0o\" 的八进制数字符串\n"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"print(bin(3)) # '0b11'\n",
"print(bin(-10)) # '-0b1010\n",
"print(hex(255)) # '0xff'\n",
"print(hex(-42)) # '-0x2a'\n",
"print(oct(8)) # '0o10'\n",
"print(oct(-56)) # '-0o70'\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## all(iterable)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"如果 iterable 的所有元素均为真值(或可迭代对象为空)则返回 True 。 等价于:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def all(iterable):\n",
" for element in iterable:\n",
" if not element:\n",
" return False\n",
" return True"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## any(iterable)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"如果 iterable 的任一元素为真值则返回 True。 如果可迭代对象为空,返回 False。 等价于:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def any(iterable):\n",
" for element in iterable:\n",
" if element:\n",
" return True\n",
" return False"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## enumerate(iterable, start=0)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"返回一个枚举对象。iterable 必须是一个序列,或 iterator,或其他支持迭代的对象。 enumerate() 返回的迭代器的 __next__() 方法返回一个元组,里面包含一个计数值(从 start 开始,默认为 0)和通过迭代 iterable 获得的值。"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"seasons = ['Spring', 'Summer', 'Fall', 'Winter']\n",
"print(list(enumerate(seasons))) #[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]\n",
"print(list(enumerate(seasons, start=1))) # [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## filter(function, iterable)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"使用 iterable 中 function 返回真值的元素构造一个迭代器。 iterable 可以是一个序列,一个支持迭代的容器或者一个迭代器。 如果 function 为 None,则会使用标识号函数,也就是说,iterable 中所有具有假值的元素都将被移除. \n",
" filter(function, iterable) 相当于一个生成器表达式,当 function 不是 None 的时候为:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"(item for item in iterable if function(item))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"function 是 None 的时候为: "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"(item for item in iterable if item) "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"## chr(i):\n",
"返回 Unicode 码位为整数 i 的字符的字符串格式。例如,chr(97) 返回字符串 'a',chr(8364) 返回字符串 '€'。这是 ord() 的逆函数。\n",
"## ord(c):\n",
"对表示单个 Unicode 字符的字符串,返回代表它 Unicode 码点的整数。例如 ord('a') 返回整数 97, ord('€') (欧元符号)返回 8364 。这是 chr() 的逆函数。"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"print(ord('a')) # 97\n",
"print(chr(97)) # a "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## max(iterable, *, key=None)\n",
"## max(iterable, *, default, key=None)\n",
"## max(arg1, arg2, *args, key=None)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"返回可迭代对象中最大的元素,或者返回两个及以上实参中最大的。\n",
"\n",
"如果只提供了一个位置参数,它必须是非空 iterable,返回可迭代对象中最大的元素;如果提供了两个及以上的位置参数,则返回最大的位置参数。"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## min(iterable, *, key=None)\n",
"## min(iterable, *, default, key=None)\n",
"## min(arg1, arg2, *args, key=None)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"返回可迭代对象中最小的元素,或者返回两个及以上实参中最小的。\n",
"\n",
"如果只提供了一个位置参数,它必须是 iterable,返回可迭代对象中最小的元素;如果提供了两个及以上的位置参数,则返回最小的位置参数。"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## isinstance(object, classinfo)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"如果 object 参数是 classinfo 参数的实例,或者是其 (直接、间接或 虚拟) 子类的实例则返回 True。 如果 object 不是给定类型的对象,则该函数总是返回 False。 如果 classinfo 是由类型对象结成的元组 (或是由其他此类元组递归生成) 或者是多个类型的 union 类型,则如果 object 是其中任一类型的实例时将会返回 True。 如果 classinfo 不是一个类型或类型元组及此类元组,则会引发 TypeError 异常。 如果之前的检查成功执行则可以不会为无效的类型引发 TypeError。"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## sorted(iterable, /, *, key=None, reverse=False)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"根据 iterable 中的项返回一个新的已排序列表。 \n",
"具有两个可选参数,它们都必须指定为关键字参数。 \n",
"key 指定带有单个参数的函数,用于从 iterable 的每个元素中提取用于比较的键 (例如 key=str.lower)。 默认值为 None (直接比较元素)。 \n",
"reverse 为一个布尔值。 如果设为 True,则每个列表元素将按反向顺序比较进行排序。 "
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"ls = [89, 25, 38, 44, 56, 100, 9]\n",
"print(sorted(ls)) # [9, 25, 38, 44, 56, 89, 100]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## reversed(seq)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"返回一个逆序的迭代器,可转列表或遍历查看"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
"ls = [89, 25, 38, 44, 56, 100, 9]\n",
"print(ls) # [89, 25, 38, 44, 56, 100, 9]\n",
"print(reversed(ls)) # <list_reverseiterator object at 0x7f59d1eaf2b0>,迭代器对象,不能直接看里面的数据\n",
"print(list(reversed(ls))) # [9, 100, 56, 44, 38, 25, 89] 可转列表查看\n",
"print(*reversed(ls)) # 9 100 56 44 38 25 89 可解包输出查看"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## map(function, iterable, *iterables)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"返回一个将 function 应用于 iterable 的每一项,并产生其结果的迭代器。 如果传入了额外的 iterables 参数,则 function 必须接受相同个数的参数并被用于到从所有可迭代对象中并行获取的项。 当有多个可迭代对象时,当最短的可迭代对象耗尽则整个迭代将会停止。 "
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [],
"source": [
"ls = [89, 25, 38, 44, 56, 100, 9]\n",
"print(map(str,ls)) # <map object at 0x7f59d1eaf3d0>\n",
"print(list(map(str,ls))) # ['89', '25', '38', '44', '56', '100', '9']\n",
"print(*map(str,ls)) # 89 25 38 44 56 100 9 解包输出,元素是字符串类型\n",
"print(list(map(float,ls))) # [89.0, 25.0, 38.0, 44.0, 56.0, 100.0, 9.0]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## open(file, mode='r', buffering=- 1, encoding=None, errors=None, newline=None, closefd=True, opener=None)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"打开 file 并返回对应的 file object。 如果该文件不能被打开,则引发 OSError。"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.5"
}
},
"nbformat": 4,
"nbformat_minor": 4
}