python内置函数详细介绍

知识内容:

1.python内置函数简介

2.python内置函数详细介绍

 

 

 

一、python内置函数简介

python中有很多内置函数,实现了一些基本功能,内置函数的官方介绍文档:    https://docs.python.org/3.6/library/functions.html

内置函数是不需要调用任何模块,可以直接在python代码中直接调用的函数

 

 

 

二、python常见内置函数详细介绍

1.数学运算

abs:求数值的绝对值

divmod:返回两个数值的商和余数

max:返回可迭代对象中的元素中的最大值或者所有参数的最大值

min:返回可迭代对象中的元素中的最小值或者所有参数的最小值

pow:返回两个数值的幂运算值或其与指定整数的模值

round:对浮点数进行四舍五入求值

sum:对元素类型是数值的可迭代对象中的每个元素求和

(1)abs:  abs(x)   ->    Return the absolute value of the argument.   返回一个数的绝对值

>>> abs(-3.34)
3.34
>>> abs(-3)
3
>>> abs(6)
6

 

(2)divmod:  divmod(x, y, /)  ->    Return the tuple (x//y, x%y).  Invariant: div*y + mod == x .   将x除y的商和余数打包成元组返回

>>> divmod(9, 3)
(3, 0)
>>> divmod(5, 2)
(2, 1)

 

(3)max: 
    max(iterable, *[, default=obj, key=func])
    max(arg1, arg2, *args, *[, key=func])
    With a single iterable argument, return its biggest item. The default keyword-only argument specifies an object to return if
    the provided iterable is empty. With two or more arguments, return the largest argument.

  对于单独的一个可迭代对象,返回它最大的一项,对于两个甚至多个变量,返回其中最大的一个变量。

>>> a = [1, 9, 3, 6 ,5]
>>> max(a)
9
>>> max(-9, -8, 9, -5, 6, 7, 12)
12
>>> max('a', 'b', 'd')
'd'
>>> max('python')
'y'

 

(4)min:和max同理,不过是返回可迭代对象中最小的一项或者返回多个值最小的一项

>>> min(1,3,5,7,-9, 8)
-9
>>> min("python")
'h'
>>> s = [1,3,6,7,9]
>>> min(s)
1

 

(5)pow:

    pow(x, y, z=None, /)  -> 提供两个变量时返回x**y的值,提供3个变量时返回x**y%z的值
    Equivalent to x**y (with two arguments) or x**y % z (with three arguments).

>>> pow(2, 3)
8
>>> pow(2, 5)
32
>>> pow(2, 10)
1024
>>> pow(2, 3, 5)
3
>>> pow(2, 5, 10)
2

 

(6)round:

    round(number[, ndigits]) -> number -> 对于一个数进行四舍五入,ndigits代表精度,是保留小数的位数,默认为0
    Round a number to a given precision in decimal digits (default 0 digits).    This returns an int when called with one argument, otherwise the same type as the number. ndigits may be negative.

>>> round(3.14156)
3
>>> round(3.14156, 1)
3.1
>>> round(3.14156, 2)
3.14
>>> round(3.14156, 3)
3.142
>>> round(3.14156, 4)
3.1416
>>> round(5.67)
6

 

(7)sum:

    sum(iterable, start=0, /)
    Return the sum of a 'start' value (default: 0) plus an iterable of numbers. When the iterable is empty, return the start value.
    This function is intended specifically for use with numeric values and may reject non-numeric types.

 返回可迭代对象的值,start是指定与结果相加的值,默认为0

>>> s = [1, 2, 3 ,4 ,7]
>>> sum(s)
17
>>> sum(s, 1)
18
>>> sum(s, 3)
20

 

 

2.类型转换

bool:根据传入的参数的逻辑值创建一个新的布尔值

int:根据传入的参数创建一个新的整数

float:根据传入的参数创建一个新的浮点数

complex:根据传入参数创建一个新的复数

str:返回一个对象的字符串表现形式(给用户)

ord:返回Unicode字符对应的整数

chr:返回整数所对应的Unicode字符

bin:将整数转换成2进制字符串

oct:将整数转化成8进制数字符串

hex:将整数转换成16进制字符串

tuple:根据传入的参数创建一个新的元组

list:根据传入的参数创建一个新的列表

dict:根据传入的参数创建一个新的字典

set:根据传入的参数创建一个新的集合

frozenset:根据传入的参数创建一个新的不可变集合

enumerate:根据可迭代对象创建枚举对象

range:根据传入的参数创建一个新的range对象

iter:根据传入的参数创建一个新的可迭代对象,即生成迭代器

(1)bool() int() float() complex() str()的使用:

 1 >>> bool(0)
 2 False
 3 >>> bool(1)
 4 True
 5 >>> int(3.3)
 6 3
 7 >>> float(3)
 8 3.0
 9 >>> str(1+2)
10 '3'
11 >>> complex(1, 3)
12 (1+3j)
13 >>> complex(1)
14 (1+0j)

 

(2)ord() chr() bin() oct() hex()的使用:

 1 >>> print(ord('?'))
 2 63
 3 >>> print(chr(98))
 4 b
 5 >>> print(bin(13))
 6 0b1101
 7 >>> print(oct(13))
 8 0o15
 9 >>> print(hex(13))
10 0xd

 

(3)tuple() list() dict() set() frozenset()的使用:

 1 >>> print(tuple([1,2,3]))
 2 (1, 2, 3)
 3 >>> print(tuple("tuple"))
 4 ('t', 'u', 'p', 'l', 'e')
 5 >>> print(list("list"))
 6 ['l', 'i', 's', 't']
 7 >>> print(dict(a='d', b='i', c='c', d='t'))
 8 {'a': 'd', 'b': 'i', 'c': 'c', 'd': 't'}
 9 >>> print(set("set"))
10 {'e', 's', 't'}
11 >>> print(frozenset("frozenset"))
12 frozenset({'f', 's', 'r', 'o', 't', 'z', 'e', 'n'})

 

(4)iter(): 生成迭代器

语法:  iter(object[, sentinel])

参数:

  • object -- 支持迭代的集合对象。
  • sentinel -- 如果传递了第二个参数,则参数 object 必须是一个可调用的对象(如,函数),此时,iter 创建了一个迭代器对象,每次调用这个迭代器对象的__next__()方法时,都会调用 object
 1 >>> for i in iter("python"):
 2 ...     print(i)
 3 ...
 4 p
 5 y
 6 t
 7 h
 8 o
 9 n
10 >>> for i in iter([1, 2, 3, 4, 5]):
11 ...     print(i)
12 ...
13 1
14 2
15 3
16 4
17 5

 

(5)enumerate(): 将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中

 1 >>> for i, j in enumerate("python"):
 2 ...     print(i, j)
 3 ...
 4 0 p
 5 1 y
 6 2 t
 7 3 h
 8 4 o
 9 5 n
10 >>> for i, j in enumerate([6,5,4,3,2,1]):
11 ...     print(i, j)
12 ...
13 0 6
14 1 5
15 2 4
16 3 3
17 4 2
18 5 1

 

(6)range():

语法:

  • range(stop)
  • range(start, stop[, step])

参数说明:

  • start: 计数从 start 开始。默认是从 0 开始。例如range(5)等价于range(0, 5);
  • stop: 计数到 stop 结束,但不包括 stop。例如:range(0, 5) 是[0, 1, 2, 3, 4]没有5
  • step:步长,默认为1。例如:range(0, 5) 等价于 range(0, 5, 1)

注:

Python3 range() 函数返回的是一个可迭代对象(类型是对象),而不是列表类型, 所以打印的时候不会打印列表。

Python3 list() 函数是对象迭代器,可以把range()返回的可迭代对象转为一个列表,返回的变量类型为列表。

Python2 range()返回的是列表

 1 >>> print(range(10))
 2 range(0, 10)
 3 >>> list(range(10))
 4 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 5 >>> for i in range(3):
 6 ...     print(i)
 7 ...
 8 0
 9 1
10 2
11 >>> for i in range(1,5,2):
12 ...     print(i)
13 ...
14 1
15 3

 

 

3.序列操作

all:判断可迭代对象的每个元素是否都为True值

any:判断可迭代对象的元素是否有为True值的元素

filter:使用指定方法过滤可迭代对象的元素

map:使用指定方法去作用传入的每个可迭代对象的元素,生成新的可迭代对象

next:返回可迭代对象中的下一个元素值

reversed:反转序列生成新的可迭代对象

sorted:对可迭代对象进行排序,返回一个新的列表

zip:聚合传入的每个迭代器中相同位置的元素,返回一个新的元组类型迭代器

(1)all():

语法:  all(iterable)  -> 可迭代参数 iterable 中的所有元素都不为 0、''、False 或者 iterable 为空,就返回 True,否则返回 False

 Return True if bool(x) is True for all values x in the iterable. If the iterable is empty, return True.

 1 >>>all(['a', 'b', 'c', 'd'])  # 列表list,元素都不为空或0
 2 True
 3 >>> all(['a', 'b', '', 'd'])   # 列表list,存在一个为空的元素
 4 False
 5 >>> all([0, 1,2, 3])          # 列表list,存在一个为0的元素
 6 False
 7 >>> all(('a', 'b', 'c', 'd'))  # 元组tuple,元素都不为空或0
 8 True
 9 >>> all(('a', 'b', '', 'd'))   # 元组tuple,存在一个为空的元素
10 False
11 >>> all((0, 1,2, 3))          # 元组tuple,存在一个为0的元素
12 False
13 >>> all([])             # 空列表
14 True
15 >>> all(())             # 空元组
16 True

 

(2)any():

语法:  any(iterable) -> 可迭代参数中有任一个值不为空或0或false就返回True,否则返回False(全部为空对象)
Return True if bool(x) is True for any x in the iterable. If the iterable is empty, return False.

 1 >>>any(['a', 'b', 'c', 'd'])  # 列表list,元素都不为空或0
 2 True
 3 >>> any(['a', 'b', '', 'd'])   # 列表list,存在一个为空的元素
 4 True
 5 >>> any([0, '', False])        # 列表list,元素全为0,'',false
 6 False
 7 >>> any(('a', 'b', 'c', 'd'))  # 元组tuple,元素都不为空或0
 8 True
 9 >>> any(('a', 'b', '', 'd'))   # 元组tuple,存在一个为空的元素
10 True
11 >>> any((0, '', False))        # 元组tuple,元素全为0,'',false
12 False
13 >>> any([]) # 空列表
14 False
15 >>> any(()) # 空元组
16 False

 

(3)filter(): -> 用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的filter对象

语法:  filter(function, iterable)

参数:

  • function -- 判断函数
  • iterable -- 可迭代对象

注:

关于filter()方法, python3和python2有一点不同,python2中返回的是过滤后的列表, 而python3中返回到是一个filter类,filter类实现了__iter__和__next__方法, 可以看成是一个迭代器, 有惰性运算的特性, 相对python2提升了性能, 可以节约内存

# 过滤出列表中的奇数
def is_odd(n):
    return n % 2 == 1
 
newlist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
for i in newlist:
    print(i)
1 #过滤出1~100中平方根是整数的数:
2 import math
3 def is_sqr(x):
4     return math.sqrt(x) % 1 == 0
5  
6 newlist = filter(is_sqr, range(1, 101))
7 for i in newlist:
8     print(i)

 

(4)map(): 根据提供的函数对指定序列做映射。

语法: map(function, *iterables)

第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回一个map对象(本质上讲是迭代器)

注: Python 2.x 返回列表;Python 3.x 返回迭代器

 1 >>> s = [-1, -3, -5, 7]
 2 >>> map(abs, s)
 3 <map object at 0x057C15B0>
 4 >>> for i in map(abs, s):
 5 ...     print(i)
 6 ...
 7 1
 8 3
 9 5
10 7

 

(5)next():  返回迭代器的下一个值

语法:

next(iterator[, default])

参数说明:

  • iterator -- 可迭代对象
  • default -- 可选,用于设置在没有下一个元素时返回该默认值,如果不设置,又没有下一个元素则会触发 StopIteration 异常
 1 # 首先获得Iterator对象:
 2 it = iter([1, 2, 3, 4, 5])
 3 # 循环:
 4 while True:
 5     try:
 6         # 获得下一个值:
 7         x = next(it)
 8         print(x)
 9     except StopIteration:
10         # 遇到StopIteration就退出循环
11         break

 

(6)reversed(seq):  返回一个反转的reversd对象(本质上是一个迭代器)   seq是要转换的序列,可以为字符串、列表、元组或range对象

 1 >>> s = [1,2,3,4,5]
 2 >>> reversed(s)
 3 <list_reverseiterator object at 0x057C1A10>
 4 >>> for i in reversed(s):
 5 ...     print(i)
 6 ...
 7 5
 8 4
 9 3
10 2
11 1

 

(7)sorted():  对可迭代对象进行排序操作

语法:

  sorted(iterable, key=None, reverse=False)

参数说明:

  • iterable -- 可迭代对象。
  • key -- 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
  • reverse -- 排序规则,reverse = True 降序 , reverse = False 升序(默认)
1 >>> sorted([1,8,9,4,5])
2 [1, 4, 5, 8, 9]
3 >>> sorted("python")
4 ['h', 'n', 'o', 'p', 't', 'y']
5 >>> sorted((3,8,2,1))
6 [1, 2, 3, 8]
7 >>> sorted([1,2,3,4,5], reverse=True)
8 [5, 4, 3, 2, 1]

 

(8)zip():  将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回zip对象

语法:

  zip([iterable, ...])

参数:

  iterable为可迭代对象

注:  如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表;Python 2.x 返回列表;Python 3.x 返回zip对象

 1 >>> a = [1,2,3]
 2 >>> b = [4,5,6]
 3 >>> zip(a, b)
 4 <zip object at 0x03357328>
 5 >>> for i, j in zip(a, b):
 6 ...     print(i, j)
 7 ...
 8 1 4
 9 2 5
10 3 6

 

 

4.对象操作

help:返回对象的帮助信息

hash:获取对象的哈希值

type:返回对象的类型,或者根据传入的参数创建一个新的类型

isinstance:判断一个对象是否是一个已知的类型,类似 type()

len:返回对象的长度

(1)help():  返回对象的帮助信息,十分有利于学习python

 1 >>> help(print)
 2 Help on built-in function print in module builtins:
 3 
 4 print(...)
 5     print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
 6 
 7     Prints the values to a stream, or to sys.stdout by default.
 8     Optional keyword arguments:
 9     file:  a file-like object (stream); defaults to the current sys.stdout.
10     sep:   string inserted between values, default a space.
11     end:   string appended after the last value, default a newline.
12     flush: whether to forcibly flush the stream.
13 
14 >>> help(dir)
15 Help on built-in function dir in module builtins:
16 
17 dir(...)
18     dir([object]) -> list of strings
19 
20     If called without an argument, return the names in the current scope.
21     Else, return an alphabetized list of names comprising (some of) the attributes
22     of the given object, and of attributes reachable from it.
23     If the object supplies a method named __dir__, it will be used; otherwise
24     the default dir() logic is used and returns:
25       for a module object: the module's attributes.
26       for a class object:  its attributes, and recursively the attributes
27         of its bases.
28       for any other object: its attributes, its class's attributes, and
29         recursively the attributes of its class's base classes.

 

(2)hash:获取对象的哈希值

语法: hash(object)

1 >>> hash("python")
2 -20878404
3 >>> hash(1)
4 1
5 >>> hash(666)
6 666
7 >>> hash('d')
8 -548204824

 注:  可变的数据类型是不可以被hash的,如果一个值可以hash那么说明这是一个不可变的数据,也就是说列表是不能hash,但是数字、字符串以及元组都可以hash

 

(3)type:返回对象的类型,或者根据传入的参数创建一个新的类型

 1 >>> type(1)
 2 <class 'int'>
 3 >>> type(3.2)
 4 <class 'float'>
 5 >>> type([])
 6 <class 'list'>
 7 >>> type(())
 8 <class 'tuple'>
 9 >>> type({})
10 <class 'dict'>

 

(4)isinstance:判断一个对象是否是一个已知的类型,类似 type()

1 >>> isinstance(3, int)
2 True
3 >>> isinstance(3.2, int)
4 False

 

注:  isinstance() 与 type() 区别:

  • type() 不会认为子类是一种父类类型,不考虑继承关系。

  • isinstance() 会认为子类是一种父类类型,考虑继承关系。

如果要判断两个类型是否相同推荐使用 isinstance()

 

(5)len:返回对象(字符、列表、元组等)的长度

1 >>> len("python")
2 6
3 >>> len([1,2,3])
4 3
5 >>> len(('a', 'b', 'c'))
6 3

 

 

5.变量操作

globals:返回当前作用域内的全局变量和其值组成的字典

locals:返回当前作用域内的局部变量和其值组成的字典

1 def func():
2     a = 12
3     b = 20
4     print(locals())
5     print(globals())
6 
7 func()

 

 

6.交互操作

print:向标准输出对象打印输出

input:读取用户输入值

注:  input无论输入什么返回的都是字符串

 1 >>> print(1, 2, 3)
 2 1 2 3
 3 >>> print("python", end="")  # 指定结尾不换行
 4 python>>> print(2, 4, 6, sep="  间距   ")   # 指定输出多个对象之间的间隔
 5 2  间距   4  间距   6
 6 >>> input(">>>")
 7 >>>3
 8 '3'
 9 >>> input("")
10 5
11 '5'
12 >>> input("请输入: ")
13 请输入: 234
14 '234'

 

 

7.文件操作

open:使用指定的模式和编码打开文件,返回文件读写对象 -> 将在文件中详细介绍

具体内容点此:  http://www.cnblogs.com/wyb666/p/8538843.html

 

8.编译执行

eval:执行动态表达式求值

注: eval()中的参数必须是字符串

1 >>> eval("3+4")
2 7
3 >>> eval("3**2")
4 9

 

 

9.面向对象

以下内置函数将在面向对象中详细介绍:

object:创建一个新的object对象

super:根据传入的参数创建一个新的子类和父类关系的代理对象

issubclass:判断类是否是另外一个类或者类型元组中任意类元素的子类

isinstance:判断一个对象是否是另一个类的对象

property:标示属性的装饰器

classmethod:标示方法为类方法的装饰器

staticmethod:标示方法为静态方法的装饰器

具体内容点此:  http://www.cnblogs.com/wyb666/p/8728621.html

 

 

 

posted @ 2018-03-28 18:58  woz333333  阅读(564)  评论(0编辑  收藏  举报