内置函数

内置函数:就是python提供给你直接可以拿来使用的所有函数    即在无需定义的情况下,直接可以用函数名()调用函数。

 

数学运算类

1.abs:求数值的绝对值

>>> abs(-2)
2       

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

>>> divmod(5,2)
(2, 1)        #这里2代表商,1代表余数

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

>>> max(-3,0,2) # 数值默认去数值较大者
3
>>> max(-1,0,key = abs) # 传入了求绝对值函数,则参数都会进行求绝对值后再取较大者
-1                  #这里比较后得到的结果任然绝对值前的数字

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

>>> min(-1,-23) # 数值默认去数值较小者
-2
>>> min(-1,-2,key = abs)  # 传入了求绝对值函数,则参数都会进行求绝对值后再取较小者
-1

5.pow:返回两个数值的幂运算值以及余数

>>> pow(2,3)
>>> 2**3    

>>> pow(2,3,5)
>>> pow(2,3)%5       

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

>>> round(1.1314926,1)
1.1
>>> round(1.1314926,5)
1.13149                  #这里的5代表小数点后保留5位

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

# 传入可迭代对象
>>> sum((1,2,3,4))
10
# 元素类型必须是数值型,可以带小数点
>>> sum((1.5,2.5,3.5,4.5))
12.0
>>> sum((1,2,3,4),10)    这里的10表示从10开始,计算时需要将其算入
20

类型转换

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

>>> bool() #不传入参数显示为False
False
>>> bool(0) #数值0、空序列等值为False
False
>>> bool(1)
True

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

>>> int() #不传入参数时,得到结果0。
0
>>> int(3)
3
>>> int(3.6)
3

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

>>> float() #不提供参数的时候,返回0.0
0.0
>>> float(3)
3.0
>>> float('3')       #传入内部为数字的字符时,可以转化为浮点数。
3.0  

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

>>> complex() #当两个参数都不提供时,返回复数 0j。
0j
>>> complex('1+2j') #传入字符串创建复数
(1+2j)
>>> complex(1,2) #传入数值创建复数
(1+2j)

str:转换为字符形式

>>> str('abc')
'abc'
>>> str(123)
'123'

bytearray和bytes

>>>b_array = bytearray('你好',encoding='utf-8')#创建一个新的可变字节数组
>>>bytearray(b'xe4xbdxa0xe5xa5xbd')     
>>>b_array = bytes('你好',encoding='utf-8')#创建一个新的不可变字节数组 >>>b'xe4xbdxa0xe5xa5xbd'

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

>>> ord('a')
97

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

>>> chr(97)
'a'

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

>>> bin(3) 
'0b11'

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

>>> oct(10)
'0o12'

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

>>> hex(15)
'0xf'

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

>>> tuple() #不传入参数,创建空元组
()
>>> tuple('121') #传入可迭代对象。使用其元素创建新的元组
('1', '2', '1')

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

>>>list() # 不传入参数,创建空列表
[] 
>>> list('abcd') # 传入可迭代对象,使用其元素创建新的列表
['a', 'b', 'c', 'd']

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

>>> dict() # 不传入任何参数时,返回空字典。
{}
>>> dict(a = 1,b = 2) #  可以传入键值对创建字典。
{'b': 2, 'a': 1}
>>> dict(zip(['a','b'],[1,2])) # 可以传入映射函数创建字典。
{'b': 2, 'a': 1}
>>> dict((('a',1),('b',2))) # 可以传入可迭代对象创建字典。
{'b': 2, 'a': 1}

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

>>>set() # 不传入参数,创建空集合
set()
>>> a = set(range(10)) # 传入可迭代对象,创建集合
>>> a
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

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

seasons = ['Spring', 'Summer', 'Fall', 'Winter']
for i in enumerate(seasons):
    print(i)              #这里结果前面显示的是列表的索引,后面显示的是与其对应的值
(0, 'Spring')
(1, 'Summer')
(2, 'Fall')
(3, 'Winter')

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

# a = range(10)
# b = range(1,10)
# c = range(1,10,3)      顾首不顾尾,3代表步长
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
# [1, 4, 7]

iter:根据传入的可迭代对象,创建一个迭代器

>>> a = iter('abcd') #字符串序列
>>> a
<str_iterator object at 0x03FB4FB0>    #此处得到一个迭代器
>>> next(a)
'a'
>>> next(a)
'b'
>>> next(a)
'c'
>>> next(a)
'd'
>>> next(a)
Traceback (most recent call last):
  File "<pyshell#29>", line 1, in <module>   
    next(a)
StopIteration

slice:根据传入的参数创建一个新的切片对象

# l = (1,2,23,213,5612,342,43)
# sli = slice(1,5,2)     #slice(1,5,2)=[1:5:2]
# print(l[sli])

序列操作

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

>>> all([1,2]) #列表中每个元素逻辑值均为True,返回True       
True
>>> all([0,1,2]) #列表中0的逻辑值为False,返回False    #元素中只要有一个是False则all返回False
False
>>> all(()) #空元组       #如果all()括号内是可迭代对象且时空的,则结果为True
True
>>> all({}) #空字典
True

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

>>> any([0,1,2]) #列表元素只要有一个为True,则返回True
True
>>> any([0,0]) #列表元素全部为False,则返回False
False
>>> any([]) #空列表     #如果all()括号内是可迭代对象且时空的,则结果为False
False
>>> any({}) #空字典
False

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

# from math import sqrt
# def func(num):
#     res = sqrt(num)   #求平方根
#     return res % 1 == 0  #取整
# ret = filter(func,range(1,10))       #filter(函数,可迭代对象)  # filter 执行了filter之后的结果集合 <= 执行之前的个数
#filter只管筛选,不会改变原来的值
#
for i in ret: # print(i) # 1 # 4 # 9

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

# ret = map(abs,[1,-4,6,-8])        #利用abs作用于可迭代对象的元素
# print(ret)
# for i in ret:
#     print(i)
#1
#4
#6
#8

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

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

>>> a = reversed(range(10)) # 传入range对象
>>> a # 转换成迭代器
<range_iterator object at 0x035634E8>
>>> list(a)
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

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

# l = [1,-4,6,5,-10]
# l.sort(key = abs)                          # 在原列表的基础上进行排序,节省内存
# print(l)

# print(sorted(l,key=abs,reverse=True)) # 生成了一个新列表 不改变原列表 占内存
结果显示:
[1, -4, 5, 6, -10]
[-10, 6, 5, -4, 1]

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

>>> x = [1,2,3] #长度3
>>> y = [4,5,6,7,8] #长度5
>>> list(zip(x,y)) # 取最小长度3
[(1, 4), (2, 5), (3, 6)]

对象操作

帮助:help 返回对象的帮助信息 

dir:返回对象或者当前作用域内的方法列表

print(dir(list))

['__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']

id:返回对象的唯一标识符(内存地址)

# k=id(1234)
# print(k)
4833008

hash:获取对象的哈希值

print(hash('abcd'))      #如果输入的对象可哈希,则显示一串数字
-1277073939423528596
print(hash([a,b.c,d]))   #如果输入的对象不可哈希,则报错
NameError: name 'a' is not defined

type:返回对象的类型

# print(type('abcd'))
<class 'str'>

len:返回对象的长度

print(len([1,2,3,4]))
4

format:格式化显示值

# format(3,'b') #转换成二进制
'11'
# format(97,'c') #转换unicode成字符
'a'
# format(11,'d') #转换成10进制
'11'
# format(11,'o') #转换成8进制
'13'
#format(11,'x') #转换成16进制 小写字母表示
'b'
# format(11,'X') #转换成16进制 大写字母表示
'B'
# format(11,'n') #和d一样
'11'
# format(11) #默认和d一样
'11'
#print(format('abcd', '<20')) #得到一个20个字节的空间,将'abcd'左对齐
#print(format('abcd', '>20'))   #得到一个20个字节的空间,将'abcd'右对齐
#print(format('abcd', '^20'))   #得到一个20个字节的空间,将'abcd'居中

动态导入模块:import

callable:检测对象是否可被调用

变量操作

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

a = 1
globals() # {
'__spec__': None, '__package__': None, '__builtins__': <module 'builtins' (built-in)>, 'a': 1, '__name__': '__main__',
'__doc__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>}

locals:返回当前作用域内的局部变量和其值组成的字典,如果将locals放入全局作用域,则结果和globals相同

>>> def f():
    print('before define a ')
    print(locals()) #作用域内无变量
    a = 1
    print('after define a')
    print(locals()) #作用域内有一个a变量,值为1
{} {a:
1} #{变量名:值}
输入输出

input:读取用户输入值

>>>s = input('please input your name:')
>>>please input your name:哈哈
>>> s
'哈哈'

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

#print(1,2,3,4,5,sep='|',end='*')
1|2|3|4|5*
print(value, ..., sep=' ', end='
', file=sys.stdout, flush=False)
file: 默认是输出到屏幕,如果设置为文件句柄,输出到文件
sep: 打印多个值之间的分隔符,默认为空格 end: 每一次打印的结尾,默认为换行符 flush: 立即把内容输出到流文件,不作缓存
文件操作

 open:使用指定的模式和编码打开文件,返回文件读写对象

#a = open('test.txt','utf-8')
#a.read()
#a.close()
编译执行

compile  函数将一个字符串编译为字节代码。

compile(source, filename, mode[, flags[, dont_inherit]])

  • source -- 字符串或者AST(Abstract Syntax Trees)对象。。
  • filename -- 代码文件名称,如果不是从文件读取代码则传递一些可辨认的值。
  • mode -- 指定编译代码的种类。可以指定为 exec, eval, single。
  • flags -- 变量作用域,局部命名空间,如果被提供,可以是任何映射对象。。
  • flags和dont_inherit是用来控制编译源码时的标志
>>> #流程语句使用exec
>>> code1 = 'for i in range(0,10): print (i)'
>>> c1 = compile(code1,'','exec')            #code1表示需要执行的字符串     ‘exec’表示指定编译代码的种类
>>> exec (c1)
0
1
2
3
4
5
6
7
8
9


>>> #简单求值表达式用eval
>>> code2 = '1 + 2 + 3 + 4'
>>> c2 = compile(code2,'','eval')
>>> eval(c2)
10

eval:执行动态表达式求值

#print(eval('1+2+3'))

6

exec:执行动态语句块

# print(exec('a=1+2')) #执行语句

3

原文地址:https://www.cnblogs.com/liusouthern/p/8193762.html