【Python】内建函数大全

数学函数

abs(x)

>>> abs(-1)
1

pow(base, exp[, mod])

>>> pow(10,2)
100

divmod(a, b)

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

可迭代类型布尔判断函数

all(iterable)

>>> all([1,2,3,4,"0",True])
True
>>> all([])
True

any(iterable)

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

代码执行函数

eval(expression[, globals[, locals]])

>>> x = 1
>>> eval("x+1")
2
>>> eval("print('hello')")
hello
>>> y = '{"a":"1","b":[1,2,3]}'
>>> eval(y)
{'a': '1', 'b': [1, 2, 3]}
>>> eval("a=1+2")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    a=1+2
     ^
SyntaxError: invalid syntax

exec(object[, globals[, locals]])

>>> a = 1
>>> b = 2
>>> exec("x=a+1\ny=a+b")
>>> x
2
>>> y
3
>>> exec("print(1);print(2)")
1
2

实例属性操作函数

class MyClass:
    a = 1
    b = 2
    def __init__(self):
        self.t = 1
    def say_hello(self):
        print("hello")

myclass = MyClass()

getattr(object, name[, default])

>>> getattr(myclass, "a")
1
>>> getattr(myclass, "c", 100)
100
>>> getattr(myclass, "c")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'MyClass' object has no attribute 'c'

>>> getattr(myclass,"say_hello")()
hello
>>> getattr(myclass,"say_hi",lambda:print("function no exists!"))()
function no exists!
>>> getattr(myclass,"say_hi")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'MyClass' object has no attribute 'say_hi'

setattr(object, name, value)

>>> setattr(myclass,"c",3)
>>> getattr(myclass, "c", 100)
3

hasattr(object, name)

>>> hasattr(myclass,"c")
True
>>> hasattr(myclass,"d")
False
>>> hasattr(myclass,"say_hello")
True

delattr(object, name)

>>> getattr(myclass,"t")
1
>>> delattr(myclass,"t")
>>> getattr(myclass,"t")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'MyClass' object has no attribute 't'

>>> delattr(myclass,"say_hello")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: say_hello
>>> del myclass.say_hello
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: say_hello

统计函数

min(iterable, *[, key, default])

>>> min([1,2,3])
1
>>> min([{"name":"a","score":80},{"name":"b","score":90},{"name":"c","score":100}],key=lambda x: x['score'])
{'name': 'a', 'score': 80}
>>> a = []
>>> t = ["iterable is empty!"]
>>> min(a, key=lambda x:x['score'], default=t)
['iterable is empty!']

min(arg1, arg2, *args[, key])

>>> min(1,2,3)
1
>>> min(6,5,4,*[3,2,1])
1
>>> min({"name":"a","score":80},{"name":"b","score":90},{"name":"c","score":100},key=lambda x: x['score'])
{'name': 'a', 'score': 80}
>>> min({"name":"a","score":80},{"name":"b","score":90},{"name":"c","score":100},*[{"name":"d","score":70},{"name":"e","score":60},{"name":"f","score":50}],key=lambda x: x['score'])
{'name': 'f', 'score': 50}

max(iterable, *[, key, default])

>>> max([1,2,3])
3
>>> max([{"name":"a","score":80},{"name":"b","score":90},{"name":"c","score":100}],key=lambda x: x['score'])
{'name': 'c', 'score': 100}
>>> a = []
>>> t = ["iterable is empty!"]
>>> max(a, key=lambda x:x['score'], default=t)
['iterable is empty!']

max(arg1, arg2, *args[, key])

>>> max(1,2,3)
3
>>> max(1,2,3,*[4,5,6])
6
>>> max({"name":"a","score":80},{"name":"b","score":90},{"name":"c","score":100},key=lambda x: x['score'])
{'name': 'c', 'score': 100}
>>> max({"name":"a","score":80},{"name":"b","score":90},{"name":"c","score":100},*[{"name":"d","score":70},{"name":"e","score":60},{"name":"f","score":50}],key=lambda x: x['score'])
{'name': 'c', 'score': 100}

sum(iterable, /, start=0)

>>> sum([1,2,3])
6
>>> sum([1,2,3],start=5)
11
>>> sum([1,2,3],5)
11

高阶函数

filter(function, iterable)

>>> a = ['a','b','c','']
>>> list(filter(lambda x:x,a))
['a', 'b', 'c']

>>> list((i for i in a if (lambda x:x)(i)))
['a', 'b', 'c']

map(function, iterable, ...)

>>> a = ['a','b','c']
>>> list(map(lambda x:x.upper(),a))
['A', 'B', 'C']

>>> a = ['a','b','c']
>>> list(((lambda x:x.upper())(i) for i in a))
['A', 'B', 'C']

进制转换函数

bin(x)

>>> bin(3)
'0b11'
>>> int('0b11',2)
3

>>> bin(-10)
'-0b1010'
>>> int('-0b1010',2)
-10

oct(x)

>>> oct(10)
'0o12'
>>> int('0o12',8)
10

>>> oct(-12)
'-0o14'
>>> int('-0o14',8)
-12

hex(x)

>>> hex(17)
'0x11'
>>> int('0x11',16)
17

>>> hex(-20)
'-0x14'
>>> int('-0x14',16)
-20

编码数值字符转换函数

chr(i)

>>> chr(97)
'a'
>>> chr(8987)
'⌛'

ord(c)

>>> ord('a')
97
>>> ord('⌛')
8987

输入输出函数

input([prompt])

>>> a = input()
hello
>>> a
'hello'

>>> b = input("please input a number:")
please input a number:1
>>> b
'1'
>>> type(b)
<class 'str'>

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

>>> print('hello world!')
hello world!
>>> print('a','b','c')
a b c
>>> print('a','b','c',sep='')
abc
>>> print(1);print(2);print(3)
1
2
3
>>> print(1,end='');print(2,end='');print(3)
123
import sys
print("a")
print("error!",file=sys.stderr)
print("b")
print("c")

在这里插入图片描述

import time
# 方法一
with open("text.txt","w") as f:
    for i in range(1,3):
        print(i,file=f,flush=True)
        time.sleep(1)

#方法二
with open("text.txt","w") as f:
    sys.stdout = f
    for i in range(1,3):
        print(i)
        sys.stdout.flush()
        time.sleep(1)

在这里插入图片描述

在这里插入图片描述

import time
with open("text.txt","w") as f:
    for i in range(1,3):
        print(i,file=f)
        time.sleep(1)

在这里插入图片描述

类型函数

class bool([x])

class complex([real[, imag]])

class int([x])

class int(x, base=10)

class float([x])

class str(object='')

class str(object=b'', encoding='utf-8', errors='strict')

class list([iterable])

class tuple([iterable])

class set([iterable])

class frozenset([iterable])

class dict(**kwarg)

class dict(mapping, **kwarg)

class dict(iterable, **kwarg)

class bytes([source[, encoding[, errors]]])

class bytearray([source[, encoding[, errors]]])

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值