Python内置函数示例

abs()

返回数字绝对值

>>> abs(-100)
100
>>> abs(10)
10
>>>

all()

判断给定的可迭代参数 iterable 中的所有元素是否都为 TRUE,如果是返回 True,否则返回 False

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

any()

判断给定的可迭代参数 iterable 是否全部为 False,则返回 False,如果有一个为 True,则返回 True

>>> any([0,0,0,0])
False
>>> any([0,0,0,1])
True
>>>

ascii()

调用对象的repr()方法,获取该方法的返回值

>>> ascii(‘test‘)
"‘test‘"
>>>

bin()

将十进制转换为二进制

>>> bin(100)
‘0b1100100‘
>>>

oct()

将十进制转换为八进制

>>> oct(100)
‘0o144‘
>>>

hex()

将十进制转换为十六进制

>>> hex(100)
‘0x64‘
>>>

bool()

测试对象是True,还是False

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

bytes()

将一个字符转换为字节类型

>>> s = "blxt"
>>> bytes(s,encoding=‘utf-8‘)
b‘blxt‘
>>>

str()

将字符、数值类型转换为字符串类型

>>> str(123)
‘123‘
>>>

callable()

检查一个对象是否是可调用的

False
>>> callable(str)
True
>>> callable(int)
True
>>> callable(0)
False
>>>

chr()

查看十进制整数对应的ASCll字符

>>> chr(100)
‘d‘
>>>

ord()

查看某个ascii对应的十进制

>>> ord(‘a‘)
97
>>>

classmethod()

修饰符对应的函数不需要实例化,不需要 self 参数,但第一个参数需要是表示自身类的 cls 参数,可以来调用类的属性,类的方法,实例化对象等

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
class A(object):
    bar = 1
    def func1(self):  
        print (‘foo‘) 
    @classmethod
    def func2(cls):
        print (‘func2‘)
        print (cls.bar)
        cls().func1()   # 调用 foo 方法

输出结果:

func2
1
foo

compile()

将字符串编译成python能识别或者可以执行的代码。也可以将文字读成字符串再编译

>>> blxt = "print(‘hello‘)"
>>> test = compile(blxt,‘‘,‘exec‘)
>>> test
<code object <module> at 0x02E9B840, file "", line 1>
>>> exec(test)
hello
>>>

complex()

创建一个复数

>>> complex(13,18)
(13+18j)
>>>

delattr()

删除对象属性

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
class Coordinate:
    x = 10
    y = -5
    z = 0
 
point1 = Coordinate() 
 
print(‘x = ‘,point1.x)
print(‘y = ‘,point1.y)
print(‘z = ‘,point1.z)
 
delattr(Coordinate, ‘z‘)
 
print(‘--删除 z 属性后--‘)
print(‘x = ‘,point1.x)
print(‘y = ‘,point1.y)
 
# 触发错误
print(‘z = ‘,point1.z)

输出结果:

>>> 
x =  10
y =  -5
z =  0
--删除 z 属性后--
x =  10
y =  -5
Traceback (most recent call last):
  File "C:\Users\fdgh\Desktop\test.py", line 22, in <module>
    print(‘z = ‘,point1.z)
AttributeError: ‘Coordinate‘ object has no attribute ‘z‘
>>>

dict()

创建数据字典

>>> dict()
{}
>>> dict(a=1,b=2)
{‘a‘: 1, ‘b‘: 2}
>>>

dir()

函数不带参数时,返回当前范围内的变量、方法和定义的类型列表

>>> dir()
[‘Coordinate‘, ‘__annotations__‘, ‘__builtins__‘, ‘__doc__‘, ‘__file__‘, ‘__loader__‘, ‘__name__‘, ‘__package__‘, ‘__spec__‘, ‘point1‘, ‘y‘]
>>>

divmod()

分别取商和余数

>>> divmod(11,2)
(5, 1)
>>>

enumerate()

返回一个可以枚举的对象,该对象的next()方法将返回一个元组

>>> blxt = [‘a‘,‘b‘,‘c‘,‘d‘]
>>> list(enumerate(blxt))
[(0, ‘a‘), (1, ‘b‘), (2, ‘c‘), (3, ‘d‘)]
>>>

eval()

将字符串str当成有效表达式来求值并返回计算结果取出字符串中内容

>>> blxt = "5+1+2"
>>> eval(blxt)
8
>>>

exec()

执行字符串或complie方法编译过的字符串,没有返回值

>>> blxt = "print(‘hello‘)"
>>> test = compile(blxt,‘‘,‘exec‘)
>>> test
<code object <module> at 0x02E9B840, file "", line 1>
>>> exec(test)
hello
>>>

filter()

过滤器,构建一个序列

#过滤列表中所有奇数
#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
def is_odd(n):
    return n % 2 == 1
 
newlist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(newlist)

输出结果:

[ 1, 3, 5, 7, 9 ]

float()

将一个字符串或整数转换为浮点数

>>> float(3)
3.0
>>> float(10)
10.0
>>>

format()

格式化输出字符串

>>> "{0} {1} {3} {2}".format("a","b","c","d")
‘a b d c‘
>>> print("网站名:{name},地址:{url}".format(name="blxt",url="www.blxt.best"))
网站名:blxt,地址:www.blxt.best
>>>

frozenset()

创建一个不可修改的集合

>>> frozenset([2,4,6,6,7,7,8,9,0])
frozenset({0, 2, 4, 6, 7, 8, 9})
>>>

getattr()

获取对象属性

>>>class A(object):
...     bar = 1
... 
>>> a = A()
>>> getattr(a, ‘bar‘)        # 获取属性 bar 值
1
>>> getattr(a, ‘bar2‘)       # 属性 bar2 不存在,触发异常
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: ‘A‘ object has no attribute ‘bar2‘
>>> getattr(a, ‘bar2‘, 3)    # 属性 bar2 不存在,但设置了默认值
3
>>>

globals()

返回一个描述当前全局变量的字典

>>> print(globals()) # globals 函数返回一个全局变量的字典,包括所有导入的变量。
{‘__builtins__‘: <module ‘__builtin__‘ (built-in)>, ‘__name__‘: ‘__main__‘, ‘__doc__‘: None, ‘a‘: ‘runoob‘, ‘__package__‘: None}

hasattr()

函数用于判断对象是否包含对应的属性

>>>class A(object):
...     bar = 1
... 
>>> a = A()
>>> hasattr(a,‘bar‘)
True
>>> hasattr(a,‘test‘)
False

hash()

返回对象的哈希值

>>>class A(object):
...     bar = 1
... 
>>> a = A()
>>> hash(a)
-2143982521
>>>

help()

返回对象的帮助文档

>>>class A(object):
...     bar = 1
... 
>>> a = A()
>>> help(a)
Help on A in module __main__ object:

class A(builtins.object)
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  bar = 1

>>>

id()

返回对象的内存地址

>>>class A(object):
...     bar = 1
... 
>>> a = A()
>>> id(a)
56018040
>>>

input()

获取用户输入内容

>>> input()
... test
‘test‘
>>>

int()

用于将一个字符串或数字转换为整型

>>> int(‘14‘,16)
20
>>> int(‘14‘,8)
12
>>> int(‘14‘,10)
14
>>>

isinstance()

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

>>> test = 100
>>> isinstance(test,int)
True
>>> isinstance(test,str)
False
>>>

issubclass()

用于判断参数 class 是否是类型参数 classinfo 的子类

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
class A:
    pass
class B(A):
    pass
    
print(issubclass(B,A))    # 返回 True

iter()

返回一个可迭代对象,sentinel可省略

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

len()

返回对象的长度

>>> dic = {‘a‘:100,‘b‘:200}
>>> len(dic)
2
>>>

list()

返回可变序列类型

>>> a = (123,‘xyz‘,‘zara‘,‘abc‘)
>>> list(a)
[123, ‘xyz‘, ‘zara‘, ‘abc‘]
>>>

map()

返回一个将function应用于iterable中每一项并输出其结果的迭代器

>>>def square(x) :            # 计算平方数
...     return x ** 2
... 
>>> map(square, [1,2,3,4,5])   # 计算列表各个元素的平方
[1, 4, 9, 16, 25]
>>> map(lambda x: x ** 2, [1, 2, 3, 4, 5])  # 使用 lambda 匿名函数
[1, 4, 9, 16, 25]
 
# 提供了两个列表,对相同位置的列表数据进行相加
>>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
[3, 7, 11, 15, 19]

max()

返回最大值

>>> max (1,2,3,4,5,6,7,8,9)
9
>>>

min()

返回最小值

>>> min (1,2,3,4,5,6,7,8)
1
>>>

memoryview()

返回给定参数的内存查看对象(memory view)

>>>v = memoryview(bytearray("abcefg", ‘utf-8‘))
>>> print(v[1])
98
>>> print(v[-1])
103
>>> print(v[1:4])
<memory at 0x10f543a08>
>>> print(v[1:4].tobytes())
b‘bce‘
>>>

next()

返回可迭代对象的下一个元素

>>> a = iter([1,2,3,4,5])
>>> next(a)
1
>>> next(a)
2
>>> next(a)
3
>>> next(a)
4
>>> next(a)
5
>>> next(a)
Traceback (most recent call last):
  File "<pyshell#72>", line 1, in <module>
    next(a)
StopIteration
>>>

object()

返回一个没有特征的新对象

>>> a = object()
>>> type(a)
<class ‘object‘>
>>>

open()

返回文件对象

>>>f = open(‘test.txt‘)
>>> f.read()
‘123/123/123‘

pow()

base为底的exp次幂,如果mod给出,取余

>>> pow (3,1,4)
3
>>>

print()

打印对象

class property()

返回property属性

class C(object):
    def __init__(self):
        self._x = None
 
    def getx(self):
        return self._x
 
    def setx(self, value):
        self._x = value
 
    def delx(self):
        del self._x
 
    x = property(getx, setx, delx, "I‘m the ‘x‘ property.")

range()

生成一个不可变序列

>>> range(10)
range(0, 10)
>>>

reversed()

返回一个反向的iterator

>>> a = ‘test‘
>>> a
‘test‘
>>> print(list(reversed(a)))
[‘t‘, ‘s‘, ‘e‘, ‘t‘]
>>>

round()

四舍五入

>>> round (3.33333333,1)
3.3
>>>

class set()

返回一个set对象,可实现去重

>>> a = [1,2,3,4,5,5,6,5,4,3,2]
>>> set(a)
{1, 2, 3, 4, 5, 6}
>>>

class slice()

返回一个表示有1range所指定的索引集的slice对象

>>> a = [1,2,3,4,5,5,6,5,4,3,2]
>>> a[slice(0,3,1)]
[1, 2, 3]
>>>

sorted()

对所有可迭代的对象进行排序操作

>>> a = [1,2,3,4,5,5,6,5,4,3,2]
>>> sorted(a,reverse=True)
[6, 5, 5, 5, 4, 4, 3, 3, 2, 2, 1]
>>>

@staticmethod

将方法转换为静态方法

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
class C(object):
    @staticmethod
    def f():
        print(‘blxt‘);
 
C.f();          # 静态方法无需实例化
cobj = C()
cobj.f()        # 也可以实例化后调用

输出结果:

test
	test

sum()

求和

a = [1,2,3,4,5,5,6,5,4,3,2]
>>> sum(a)
40
>>>

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

tuple()

不可变的序列类型

>>> a = ‘www‘
>>> b =tuple(a)
>>> b
(‘w‘, ‘w‘, ‘w‘)
>>>

zip()

将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表

>>>a = [1,2,3]
>>> b = [4,5,6]
>>> c = [4,5,6,7,8]
>>> zipped = zip(a,b)     # 打包为元组的列表
[(1, 4), (2, 5), (3, 6)]
>>> zip(a,c)              # 元素个数与最短的列表一致
[(1, 4), (2, 5), (3, 6)]
>>> zip(*zipped)          # 与 zip 相反,*zipped 可理解为解压,返回二维矩阵式
[(1, 2, 3), (4, 5, 6)]

点击这里跳转个人博客

相关推荐