python内置函数

pyhton内置函数如下表:

 内置函数的详细解读:

 1.abs(x):绝对值函数

>>> abs(-1)
1

2.all(iterable):迭代器所有元素为真或空,返回True,否则,返回False

>>> all([1,3,0,3])
False
>>> all(())
True

 

3.any(iterable):迭代器任意元素为真返回True,为空,返回False

>>> any((1,2,3))
True
>>> any([])
False

 

4.ascii(object):返回一个可打印的字符串,如果是非Ascii编码的字符,返回带有\x,\u,\U转义

>>> ascii("")
"'\\u5f20'"
>>> ascii("a")
"'a'"
>>> ascii('a')
"'a'"
>>> ascii('A')
"'A'"

 

5.bin(x):将一个整数转换为前置为0b的二进制。如果括弧内的不是整数,则需要则需要定义_index_返回一个整数

>>> bin(3)
'0b11'
>>> bin(-3)
'-0b11'

 6.bool(x):返回一个boo值,True或者False

>>> bool((1))
True
>>> bool(())
False

 7.breakpoint(*args,*kws):此函数会在调用sys.breakpoint(),陷入调试器中

8.bytearray([source[, encoding[, errors]]]):返回一个新的bytes数组,是一个可变序列,范围在0<=x<256

如果 source 为整数,则返回一个长度为 source 的初始化数组;
如果 source 为字符串,则按照指定的 encoding 将字符串转换为字节序列;
如果 source 为可迭代类型,则元素必须为[0 ,255] 中的整数;
如果 source 为与 buffer 接口一致的对象,则此对象也可以被用于初始化 bytearray。
如果没有输入任何参数,默认就是初始化数组为0个元素。
>>>bytearray()
bytearray(b'')
>>> bytearray([1,2,3])
bytearray(b'\x01\x02\x03')
>>> bytearray('runoob', 'utf-8')
bytearray(b'runoob')

 

9.bytes([source[, encoding[, errors]]]):返回一个新的bytes对象,是一个不可变序列,范围在0<=x<256

如果 source 为整数,则返回一个长度为 source 的初始化数组;
如果 source 为字符串,则按照指定的 encoding 将字符串转换为字节序列;
如果 source 为可迭代类型,则元素必须为[0 ,255] 中的整数;
如果 source 为与 buffer 接口一致的对象,则此对象也可以被用于初始化 bytearray。
如果没有输入任何参数,默认就是初始化数组为0个元素。
>>>a = bytes([1,2,3,4])
>>> a
b'\x01\x02\x03\x04'
>>> a = bytes('hello','ascii')
>>> a
b'hello'

 

10.callable(object):如果实参可调用返回True,否则,返回False。如果实例的类有_call_方法,则可调用

11.chr():用整数做参数(即0~255),返回一个对应的字符

>>> chr(98)
'b'

12.classmethod():将一个方法封装成类

13.compile():将一个字符串编译成字节代码

>>> str = '3*4 + 5'
>>> a = compile(str,'','eval')
>>> eval(a)
17
>>> str = "for i in range(0,10):print(i)"
>>> c = compile(str,'','exec')
>>> exec(c)
0
1
2
3
4
5
6
7
8
9

 14.complex():用于创建一个值为 real + imag * j 的复数或者转化一个字符串或数为复数。如果第一个参数为字符串,则不需要指定第二个参数

    real -- int, long, float或字符串;

     imag -- int, long, float

>>>complex(1, 2)
(1 + 2j)
 
>>> complex(1)    # 数字
(1 + 0j)
 
>>> complex("1")  # 当做字符串处理
(1 + 0j)
 
# 注意:这个地方在"+"号两边不能有空格,也就是不能写成"1 + 2j",应该是"1+2j",否则会报错
>>> complex("1+2j")
(1 + 2j)

15.delattr():用于删除属性

16.dict():用于创建一个字典

>>> dict()
{}
>>> dict(a = 'a',b = 'b')
{'a': 'a', 'b': 'b'}
>>> dict(zip(['one','two','three'],[1,2,3]))
{'one': 1, 'two': 2, 'three': 3}
>>> dict([('one',1),('two',2)])
{'one': 1, 'two': 2}

17.dir():dir不带参数时返回当前范围内的变量、方法和定义的类型列表,带参数时返回参数的属性、列表方法。如果该参数包含_dir_()则该方法将被调用,如果不包含,则最大限度的收集参数信息。

>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'a', 'c', 'i', 'str']
>>> dir([])
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

18.divmod(x,y):把除数和余数结合起来,结果是包含商和余数的元组

>>> divmod(10,3)
(3, 1)

 19.emumrate():用于将一个可遍历的对象组合成索引对象

>>> seasons = ['sprong','summer','fall']
>>> list(enumerate(seasons))
[(0, 'sprong'), (1, 'summer'), (2, 'fall')]
>>> list(enumerate(seasons,start = 1))
[(1, 'sprong'), (2, 'summer'), (3, 'fall')]

 20.eval():用于执行一个字符串表达式,并且返回字符串的值

>>> eval('2*4')
8

21.exec():执行更复杂的python语句

>>>exec 'print "Hello World"'
Hello World
# 单行语句字符串
>>> exec "print 'runoob.com'"
runoob.com

22.filter():用于过滤

23.float():用于将整数和字符串转换成浮点数

24.format():字符串的格式转换

>>>"{} {}".format("hello", "world")    # 不设置指定位置,按默认顺序
'hello world'
 
>>> "{0} {1}".format("hello", "world")  # 设置指定位置
'hello world'
 
>>> "{1} {0} {1}".format("hello", "world")  # 设置指定位置
'world hello world'

25.frozenset():返回一个冻结的集合。冻结后不可删除或添加元素

>>>a = frozenset(range(10))     # 生成一个新的不可变集合
>>> a
frozenset([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> b = frozenset('runoob') 
>>> b
frozenset(['b', 'r', 'u', 'o', 'n'])   # 创建不可变集合
>>>

26.getattr():用于返回一个对象属性值

27.globals():以字典类型返回当前位置的全部全局变量

28.hasattr():用于判断对象是否包含对应的属性

29.hash():用于获取一个对象的哈希值

30.hex():用于将十进制转换成十六进制,以字符串的形式表示

31.id():用于获取对象的内存地址

32.input():输入

33.int():用于将字符串或数字转换成整型

34.isinstense():用于判断一个对象是否是已知类型

>>>a = 2
>>> isinstance (a,int)
True
>>> isinstance (a,str)
False
>>> isinstance (a,(str,int,list))    # 是元组中的一个返回 True
True

35.issubclass(calss,classinfo):用于判断参数 class 是否是类型参数 classinfo 的子类

36.iter():用于生成迭代器

>>> lst = [1,2,3]
>>> for i in iter(lst):
    print(i)

    
1
2
3

37.len():返回对象长度或对象个数

>>>str = "runoob"
>>> len(str)             # 字符串长度
6
>>> l = [1,2,3,4,5]
>>> len(l)               # 列表元素个数
5

38.list():用于将元组转换为列表。

注:元组与列表是非常类似的,区别在于元组的元素值不能修改,元组是放在括号中,列表是放于方括号中。

>>> tuple = (1,2,'hello')
>>> List = list(tuple)
>>> print(List)
[1, 2, 'hello']

39.locals():以字典形式返回当前位置的全部局部变量

40.map():根据函数做相应的映射

>>> map(lambda x: x*2 ,[1,2,3])
<map object at 0x0000000002AD7D30>

41.max():返回给定参数的最大值,参数可以作为序列

42.memoryview ():返回给定参数的内存查看对象

43.min():返回给定参数的最小值,参数可以作为序列

44.next():返回迭代器的下一项,通过调用 iterator 的 __next__()方法获取下一个元素。

# 首先获得Iterator对象:
it = iter([1, 2, 3, 4, 5])
# 循环:
while True:
    try:
        # 获得下一个值:
        x = next(it)
        print(x)
    except StopIteration:
        # 遇到StopIteration就退出循环
        break

45.object():所有类的基类

46.oct():将一个整数转化成八进制字符串

47.open():打开一个文件,创建一个file对象

48.ord():ord() 函数是 chr() 函数(对于8位的ASCII字符串)或 unichr() 函数(对于Unicode对象)的配对函数,它以一个字符(长度为1的字符串)作为参数,返回对应的 ASCII 数值,或者 Unicode 数值,如果所给的 Unicode 字符超出了你的 Python 定义范围,则会引发一个 TypeError 的异常。

49.pow():返回 xy(x的y次方) 的值

>>> pow(2,3)
8

50.print():打印输出

51.property():新式类中返回属性值

52.range():创建一个整数列表,一般和for循环结合使用

>>> for i in range(1,3):
    print(i)

    
1
2

53.repr():将对象转化为供解释器读取的形式。

54.reverse():用于反向列表中元素

55.round():返回浮点数x的四舍五入值

>>> print(round(20.33333,3))
20.333

56.set():创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算交集、差集、并集等。

>>>x = set('runoob')
>>> y = set('google')
>>> x, y
(set(['b', 'r', 'u', 'o', 'n']), set(['e', 'o', 'g', 'l']))   # 重复的被删除
>>> x & y         # 交集
set(['o'])
>>> x | y         # 并集
set(['b', 'e', 'g', 'l', 'o', 'n', 'r', 'u'])
>>> x - y         # 差集
set(['r', 'b', 'u', 'n'])
>>>

57.slice():切片操作

>>>myslice = slice(5)    # 设置截取5个元素的切片
>>> myslice
slice(None, 5, None)
>>> arr = range(10)
>>> arr
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> arr[myslice]         # 截取 5 个元素
[0, 1, 2, 3, 4]
>>>

57.sorted():对所有可迭代对象进行排序操作

>>>a = [5,7,6,3,4,1,2]
>>> b = sorted(a)       # 保留原列表
>>> a 
[5, 7, 6, 3, 4, 1, 2]
>>> b
[1, 2, 3, 4, 5, 6, 7]
 
>>> L=[('b',2),('a',1),('c',3),('d',4)]
>>> sorted(L, cmp=lambda x,y:cmp(x[1],y[1]))   # 利用cmp函数
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]
>>> sorted(L, key=lambda x:x[1])               # 利用key
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]
 
 
>>> students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
>>> sorted(students, key=lambda s: s[2])            # 按年龄排序
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
 
>>> sorted(students, key=lambda s: s[2], reverse=True)       # 按降序
[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
>>>

58.staticmethod ():返回函数的静态方法

59.str():将对象转换成事宜阅读的形式

60.sum():计算总和

61.super():调用父类的方法

class A:
     def add(self, x):
         y = x+1
         print(y)
class B(A):
    def add(self, x):
        super().add(x)
b = B()
b.add(2)  # 3

62.type():如果你只有第一个参数则返回对象的类型,三个参数返回新的类型对象

63.vars():返回对象object的属性和属性值的字典对象

64.zip():用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的对象,这样做的好处是节约了不少的内存。我们可以使用 list() 转换来输出列表。如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。

>>>a = [1,2,3]
>>> b = [4,5,6]
>>> c = [4,5,6,7,8]
>>> zipped = zip(a,b)     # 返回一个对象
>>> zipped
<zip object at 0x103abc288>
>>> list(zipped)  # list() 转换为列表
[(1, 4), (2, 5), (3, 6)]
>>> list(zip(a,c))              # 元素个数与最短的列表一致
[(1, 4), (2, 5), (3, 6)]
 
>>> a1, a2 = zip(*zip(a,b))          # 与 zip 相反,zip(*) 可理解为解压,返回二维矩阵式
>>> list(a1)
[1, 2, 3]
>>> list(a2)
[4, 5, 6]
>>>

65._import_:用于动态加载类和函数

posted @ 2019-10-24 22:16  行之!  阅读(232)  评论(0编辑  收藏  举报