码迷,mamicode.com
首页 > 其他好文 > 详细

内置函数

时间:2018-06-21 18:30:53      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:...   bytes   JD   ted   cfa   hfs   format   sgi   name   

技术分享图片内置函数

内置函数

技术分享图片

作用域类型相关

 ***locals

函数会以字典的类型返回当前位置的全部局部变量。(返回字典)

 ***globals

函数以字典的类型返回全部全局变量。(返回字典)

其他相关

 字符串类型代码的执行 eval,exec,complie

  ***eval

执行字符串类型的代码,并返回最终结果。(有返回值的)

print(‘1 + 3‘)

print(eval(‘1+3‘))

print(eval(‘3 * 3‘))

dic = eval("{‘name‘: ‘alex‘}")

print(dic,type(dic)

  ***exec

执行字符串类型的代码。(没有返回值的)

code = ‘‘‘

for i in range(1, 11):

print(i)

‘‘‘

exec(code)

  *compile

将字符串类型的代码编译。代码对象能够通过exec语句来执行或者eval()进行求值。(几乎不用)

 输入输出相关input,print

  ***input

函数接受一个标准输入数据,返回为 string 类型

  ***print

打印输出

print(1,2,3,sep=‘|‘) # 设置每个元素的连接符 sep=‘|‘

print(666,end=‘‘) # end=‘\n‘ 默认换行

print(555)

f1 = open(‘log‘, encoding=‘utf-8‘, mode=‘w‘)

print(‘随便写的内容‘,file=f1)

 内存相关 hash id

  **hash

获取一个对象(可哈希对象:int,str,Bool,tuple)的哈希值。(1 <class ‘int‘>)

 

print(hash(‘name‘))

print(hash(7117817419752622577))

print(hash(‘name1‘))

print(hash(‘name2‘))

print(hash(‘name3‘))

print(hash(100))

print(hash(1))

print(hash(True))

  **id

用于获取对象的内存地址。(34172584 <class ‘int‘>)

 文件操作相关

  ***open

函数用于打开一个文件,创建一个 file 对象,相关的方法才可以调用它进行读写。(获得的文件句柄为一个迭代器)

 模块相关_import

  *__import__

函数用于动态加载类和函数

 **帮助help

函数用于查看函数或模块用途的详细说明

 调用相关

  **callable

函数用于检查一个对象是否是可调用的。如果返回True,object仍然可能调用失败;但如果返回False,调用对象ojbect绝对不会成功

 

def func1():

print(111)

a = 666

print(callable(a))

print(callable(func1))

 查看内置属性

  dir

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

 

print(dir(str))

print(dir(‘abc‘))

迭代器生成器相关

 ***range

函数可创建一个整数对象,一般用在 for 循环中。

 **next

内部实际使用了__next__方法,返回迭代器的下一个项目。

 

# 首先获得Iterator对象:

it = iter([1, 2, 3, 4, 5])

# 循环:

while True:

try:

# 获得下一个值:

x = next(it)

print(x)

except StopIteration:

# 遇到StopIteration就退出循环

break

 **iter

函数用来生成迭代器(将一个可迭代对象,生成迭代器)

 

from collections import Iterable

from collections import Iterator

l = [1,2,3]

print(isinstance(l,Iterable)) # True

print(isinstance(l,Iterator)) # False

 

l1 = iter(l)

print(isinstance(l1,Iterable)) # True

print(isinstance(l1,Iterator)) # True

基础数据类型相关

 数字相关

  数据类型 4个

   **bool

用于将给定参数转换为布尔类型,如果没有参数,返回 False

 

print(bool(‘‘))

   ***int

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

 

print(int()) # 0

 

print(int(‘12‘)) # 12

 

print(int(3.6)) # 3

 

print(int(‘0100‘,base=2)) # 将2进制的 0100 转化成十进制。结果为 4

   ***float

float:函数用于将整数和字符串转换成浮点数。

 

   *complex

>>>complex(1, 2)

(1 + 2j)

 

>>> complex(1) # 数字

(1 + 0j)

 

>>> complex("1") # 当做字符串处理

(1 + 0j)

 

# 注意:这个地方在"+"号两边不能有空格,也就是不能写成"1 + 2j",应该是"1+2j",否则会报错

>>> complex("1+2j")

(1 + 2j)

  进制转换 3个

   *bin

bin:将十进制转换成二进制并返回。

 

# print(bin(3)) # 0b11

   *oct

将十进制转化成八进制字符串并返回。

# print(oct(9)) # 0o11

# print(oct(10)) # 0o11

   *hex

将十进制转化成十六进制字符串并返回。

# print(hex(10)) # 0xa

# print(hex(15)) # 0xf

# print(hex(17)) # 0x11

  数学运算 7个

   **abs

函数返回数字的绝对值。

# print(abs(-5)) # 5

   **divmod

计算除数与被除数的结果,返回一个包含商和余数的元组(a // b, a % b)。

# print(divmod(7,3))

# print(divmod(103,8))

   * round

保留浮点数的小数位数,默认保留整数。

# print(round(2.3287654)) # 默认保留整数

# print(round(2.3987654, 2)) #

   *pow

求x**y次幂。(三个参数为x**y的结果对z取余)

# print(pow(3,3)) # pow(x,y) x ** y

# print(pow(3,3,5)) # pow(x,y) x ** y

   *** sum

对可迭代对象进行求和计算(可设置初始值与迭代对象的和再相加)。

# l1 = [1, 2, 3, 55, 77]

# print(sum(l1))

# print(sum(l1,100)) # 设置初始值

   *** min

返回可迭代对象的最小值(可加key,key为函数名,通过函数的规则,返回最小值)。

l1 = [1, 2, 3, 55, 77]

l2 = [-1, -2, 3, 55, -77]

# print(min(l1))

# print(min(l2,key=abs))

   *** max

返回可迭代对象的最大值(可加key,key为函数名,通过函数的规则,返回最大值)。

# print(max(l1))

# print(max(l2,key=abs))

# dic = {‘a‘: 3,‘b‘: 2,‘c‘: 1}

# def func(x): return dic[x]

# print(min(dic,key=func))

# print(max(dic,key=func))

# lis = [[1517991992.94, 100], [1517992000.94, 200], [1517992014.94, 300], [1517992744.94, 350], [1517992800.94, 280]]

# def func1(x): return x[1]

# print(max(lis,key=func1))

 和数据结构相关 24个

  列表和元祖 2个

   **list

将一个可迭代对象转化成列表(如果是字典,默认将key作为列表的元素)。

# l1 = [1,2,3]

# l2 = list([1,2,3]) #创建列表

# l3 = list((1,2,3))

# print(l3)

   **tuple

将一个可迭代对象转化成元祖(如果是字典,默认将key作为元祖的元素)

  相关内置函数 2个

   *** reversed

l1 = [22, 33, 55, 11]

# print(reversed(l1))

# for i in reversed(l1):

# print(i)

   ** slice

构造一个切片对象,用于列表的切片。

# l1 = [1, 2, 3, 55, 77]

# l2 = [-1, -2, 3, 55, -77, 88]

# print(l1[1:4])

# print(l2[1:4])

# rule = slice(1,6,2)

# print(l1[rule])

# print(l2[rule])

  字符串相关 9个

   ***str

将数据转化成字符串。

   *format

与字符串的方法(str.format())不一样。

与具体数据相关,用于计算各种小数,精算等。

 

#字符串可以提供的参数,指定对齐方式,<是左对齐, >是右对齐,^是居中对齐

print(format(‘test‘, ‘<20‘))

print(format(‘test‘, ‘>20‘))

print(format(‘test‘, ‘^20‘))

 

#整形数值可以提供的参数有 ‘b‘ ‘c‘ ‘d‘ ‘o‘ ‘x‘ ‘X‘ ‘n‘ None

>>> 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‘

 

#浮点数可以提供的参数有 ‘e‘ ‘E‘ ‘f‘ ‘F‘ ‘g‘ ‘G‘ ‘n‘ ‘%‘ None

>>> format(314159267,‘e‘) #科学计数法,默认保留6位小数

‘3.141593e+08‘

>>> format(314159267,‘0.2e‘) #科学计数法,指定保留2位小数

‘3.14e+08‘

>>> format(314159267,‘0.2E‘) #科学计数法,指定保留2位小数,采用大写E表示

‘3.14E+08‘

>>> format(314159267,‘f‘) #小数点计数法,默认保留6位小数

‘314159267.000000‘

>>> format(3.14159267000,‘f‘) #小数点计数法,默认保留6位小数

‘3.141593‘

>>> format(3.14159267000,‘0.8f‘) #小数点计数法,指定保留8位小数

‘3.14159267‘

>>> format(3.14159267000,‘0.10f‘) #小数点计数法,指定保留10位小数

‘3.1415926700‘

>>> format(3.14e+1000000,‘F‘) #小数点计数法,无穷大转换成大小字母

‘INF‘

 

#g的格式化比较特殊,假设p为格式中指定的保留小数位数,先尝试采用科学计数法格式化,得到幂指数exp,如果-4<=exp<p,则采用小数计数法,并保留p-1-exp位小数,否则按小数计数法计数,并按p-1保留小数位数

>>> format(0.00003141566,‘.1g‘) #p=1,exp=-5 ==》 -4<=exp<p不成立,按科学计数法计数,保留0位小数点

‘3e-05‘

>>> format(0.00003141566,‘.2g‘) #p=1,exp=-5 ==》 -4<=exp<p不成立,按科学计数法计数,保留1位小数点

‘3.1e-05‘

>>> format(0.00003141566,‘.3g‘) #p=1,exp=-5 ==》 -4<=exp<p不成立,按科学计数法计数,保留2位小数点

‘3.14e-05‘

>>> format(0.00003141566,‘.3G‘) #p=1,exp=-5 ==》 -4<=exp<p不成立,按科学计数法计数,保留0位小数点,E使用大写

‘3.14E-05‘

>>> format(3.1415926777,‘.1g‘) #p=1,exp=0 ==》 -4<=exp<p成立,按小数计数法计数,保留0位小数点

‘3‘

>>> format(3.1415926777,‘.2g‘) #p=1,exp=0 ==》 -4<=exp<p成立,按小数计数法计数,保留1位小数点

‘3.1‘

>>> format(3.1415926777,‘.3g‘) #p=1,exp=0 ==》 -4<=exp<p成立,按小数计数法计数,保留2位小数点

‘3.14‘

>>> format(0.00003141566,‘.1n‘) #和g相同

‘3e-05‘

>>> format(0.00003141566,‘.3n‘) #和g相同

‘3.14e-05‘

>>> format(0.00003141566) #和g相同

‘3.141566e-05‘

   *bytes

用于不同编码之间的转化。 将unicode ---> bytes

 

unicode ---> utf-8

# s1 = ‘alex‘

# b1 = s1.encode(‘utf-8‘)

# b1 = bytes(s1,encoding=‘utf-8‘)

# print(b1)/

# print(b1)

# s2 = b1.decode(‘utf-8‘)

# print(s2)

# s1 = ‘中国‘

# b1 = s1.encode(‘utf-8‘)

# b2 = b1.decode(‘utf-8‘).encode(‘gbk‘)

# print(b2)

   *bytearry

返回一个新字节数组。这个数组里的元素是可变的,并且每个元素的值范围: 0 <= x < 256。

# ret = bytearray(‘alex‘, encoding=‘utf-8‘) # [97,104,101,109]

# print(id(ret))

# # print(ret)

# print(ret[0])

# ret[0] = 65

# print(ret) # [65,104,101,109]

# print(id(ret))

   *memoryview

ret = memoryview(bytes(‘你好‘,encoding=‘utf-8‘)) # [\xe4,\xbd,\xa0,\xe5,\xa5,\xbd]

# print(len(ret)) # 6

# print(ret)

# print(bytes(ret[:3]).decode(‘utf-8‘))

# print(bytes(ret[3:]).decode(‘utf-8‘))

   *ord

输入字符找该字符编码的位置 unicode的编码

# print(ord(‘a‘))

# print(ord(‘我‘))

   *chr

输入位置数字找出其对应的字符 unicode

# print(chr(97))

   *ascii

是ascii码中的返回该值,不是就返回 / u...

# print(ascii(‘a‘))

# print(ascii(‘中国‘)) # ‘\u4e2d\u56fd‘

   ** repr

返回一个对象的string形式(原形毕露)。

# print(repr(‘中国‘))

# print(repr(‘{"name": "alex"}‘))

# s1 = ‘我是%s人‘ % (‘中国‘)

# s2 = ‘我是%r人‘ % (‘中国‘)

# print(s1)

# print(s2)

 数据集合(3)

  ***dict

创建一个字典

  ***set

创建一个集合。

  **frozenset

返回一个冻结的集合,冻结后集合不能再添加或删除任何元素。

 相关内置函数 8个

  ***len

返回一个对象中元素的个数。

  ***sorted

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

 

l1 = [1, 4, 5, 77, 2, 3,]

# print(sorted(l1))

# L = [(‘a‘, 4), (‘c‘, 3), (‘d‘, 1),(‘b‘, 2), ]

# def func2(x):

# return x[1]

# l2 = sorted(L,key=func2)

# print(l2)

  ***enumerate

枚举,返回一个枚举对象。

print(enumerate([1,2,3]))

for i in enumerate([1,2,3]):

print(i)

for i in enumerate([1,2,3],100):

print(i)

 

  **all

可迭代对象中,全都是True才是True

 

l1 = [‘asv‘, 1, True]

# print(all(l1))

  **any

可迭代对象中,有一个True

l2 = [True,"", 0, ()]

# print(any(l2))

  ***zip

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

# 如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同。

# l1 = [1, 2, 3,]

# l2 = [‘a‘,‘b‘,‘c‘,5]

# l3 = (‘*‘,‘**‘,(1,2,3), 2, 4)

# print(zip(l1,l2,l3)) 可以视为:[(1, ‘a‘, ‘*‘),(2, ‘b‘, ‘**‘),(3, ‘c‘, (1, 2, 3))]

# for i in zip(l1,l2,l3):

# print(i)

  *** filter

过滤·。相当于列表推导式里的过滤

# def func(x):

# return x % 2 == 0

# ret = filter(func,[1,2,3,4,5,6,7])

# print(ret)

# for i in ret:

# print(i)

# print((i for i in [1,2,3,4,5,6,7] if i % 2 == 0))

  ***map

会根据提供的函数对指定序列做映射。

相当于列表推导式里的循环

# l1 = [1,2,3,4,5]

# def func(x):

# return x*x

# ret = map(func,l1)

# print(ret)

# for i in ret:

# print(i)

内置函数

标签:...   bytes   JD   ted   cfa   hfs   format   sgi   name   

原文地址:https://www.cnblogs.com/mjc69213/p/9210338.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!