四:内置函数

https://blog.csdn.net/alice_tl/article/details/80867196

1,内置函数简介

函数就是以功能为导向,一个函数封装一个功能,那么Python将一些常用的功能(比如len)给我们封装成了一个一个的函数,供我们使用,他们不仅效率高(底层都是用C语言写的),而且是拿来即用,避免重复早轮子,那么这些函数就称为内置函数,到目前为止python给我们提供的内置函数一共是68个

all()  any()  bytes() callable() chr() complex() divmod() eval() exec() format() frozenset() globals() hash() help() id() input() int()  iter() locals() next()  oct()  ord()  pow()    repr()  round()

重点:

  classmethod()  abs() enumerate() filter()  map() max()  min() open()  range() print()  len()  list()  dict() str()  float() reversed()  set()  sorted()  sum()    tuple()  type()  zip()  dir() delattr() getattr() hasattr()  issubclass()  isinstance()  object() property()  setattr()  staticmethod()  super()

2,内置函数的分类

2.1 基础数据类型相关(38)

2.1.1 和数字相关

  1,数据类型(4)

    bool,int,float,complex

  2,进制转换(3)

    bin(),oct(),hex()

print(bin(10))  # ==>二进制  0b1010
print(oct(10))  # ==>八进制  0o12
print(hex(10)) # ==>十六进制  0xa

  3,数学运算

    abs(),divmod(),round(),pow(),sum(),min(),max()

print(abs(-5)) #==>5
print(abs(5))  #==>5

print(divmod(7,2))   # div除法 mod取余   ==>(3, 1)
print(divmod(9,5))   # 取余   ==>(1, 4)

print(round(3.14159,3))  # ==> 3.142
print(pow(2,3))   #pow幂运算  == 2**3=8
print(pow(3,2))  # ==>9
print(pow(2,3,3)) #幂运算之后再取余  ==>2
print(pow(3,2,1))  # ==> 0

ret = sum([1,2,3,4,5,6])
print(ret)  # ==> 21

ret = sum([1,2,3,4,5,6,10],)
print(ret) # ==>31

print(min([1,2,3,4]))  #==>1
print(min(1,2,3,4))  #==>1
print(min(1,2,3,-4)) #==>-4
print(min(1,2,3,-4,key = abs))  #==>1

print(max([1,2,3,4]))  #==>4
print(max(1,2,3,4)) #==>4
print(max(1,2,3,-4)) #==>3
print(max(1,2,3,-4,key = abs))  #==>-4
View Code

2.1.2 和数据结构相关

  1,序列(13)

    列表和元祖(2)

      list(),tuple()

    相关内置函数(2)

      reversed(),slice(),

# reversed()
l = [1,2,3,4,5]
l.reverse()
print(l)
l = [1,2,3,4,5]
l2 = reversed(l)
print(l2)
# 保留原列表,返回一个反向的迭代器

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

    字符串(9)

      str(),format(),bytes(),bytearry(),memoryview(),ord(),chr(),ascii(),repr()

print(format('test', '<20'))
print(format('test', '>40'))
print(format('test', '^40'))
'''
test                
                                    test
                  test                  
'''

#bytes 转换成bytes类型
# 我拿到的是gbk编码的,我想转成utf-8编码
print(bytes('你好',encoding='GBK'))     # unicode转换成GBK的bytes
print(bytes('你好',encoding='utf-8'))   # unicode转换成utf-8的bytes

# 网络编程 只能传二进制
# 照片和视频也是以二进制存储
# html网页爬取到的也是编码
b_array = bytearray('你好',encoding='utf-8')
print(b_array)
print(b_array[0])
'\xe4\xbd\xa0\xe5\xa5\xbd'
s1 = 'alexa'
s2 = 'alexb'

l = 'ahfjskjlyhtgeoahwkvnadlnv'
l2 = l[:10]

# 切片 —— 字节类型  不占内存
# 字节 —— 字符串 占内存

print(ord('')) # ==>22909
print(ord('1')) # ==>49
print(chr(97))  # ==>a

print(ascii('')) # ==>'\u597d'
print(ascii('1'))  # ==>'1'
name = 'egg'
print('你好%r'%name)  # ==>你好'egg'
print(repr('1'))  # ==>'1'
print(repr(1))  # ==>1
print('1')  # ==>1
View Code

  2,数据集合(3)

    字典(1)

      dict()

    集合(2)

      set(),frozent()

  3,相关内置函数(8)

    len(),sorted(),enumerate(),all(),any(),zip(),fiter(),map()

# all() any()
print(all(['a','',123]))  #==>False
print(all(['a',123]))  #==>True
print(all([0,123]))  #==>False
print(any(['',True,0,[]]))  #==>True


# zip
l = [1,2,3,4,5]
l2 = ['a','b','c','d']
l3 = ('*','**',[1,2])
d = {'k1':1,'k2':2}
for i in zip(l,l2,l3,d):
     print(i)

# filter(),map()
# filter 执行了filter之后的结果集合 <= 执行之前的个数
# filter只管筛选,不会改变原来的值
# map 执行前后元素个数不变
# 值可能发生改变
def is_odd(x):
    return x % 2 == 1

def is_str(s):
    return s and str(s).strip()

ret = filter(is_odd, [1,  6, 7, 12, 17])
ret1 = filter(is_str, [1, 'hello','','  ',None,[], 6, 7, 'world', 12, 17])
print(ret)
print(ret1)
for i in ret:
    print(i)
for i in ret1:
    print(i)
# 相当于:[i for i in [1, 4, 6, 7, 9, 12, 17] if i % 2 == 1]

# 例子
from math import sqrt
def func(num):
    res = sqrt(num)
    return res % 1 == 0
ret = filter(func,range(1,101))
for i in ret:
    print(i)

ret = map(abs,[1,-4,6,-8])
print(ret)
for i in ret:
    print(i)

# sorted():  生成了一个新列表 不改变原列表 占内存
l = [1,-4,6,5,-10]
l.sort(key = abs)   # 在原列表的基础上进行排序
print(l)
print(sorted(l,key=abs,reverse=True))      # 生成了一个新列表 不改变原列表 占内存
print(l)

l = ['   ',[1,2],'hello world']
new_l = sorted(l,key=len)
print(new_l)
View Code

 

 

2.2 作用域相关(2)

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

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

print(locals())  #返回本地作用域中的所有名字
print(globals()) #返回全局作用域中的所有名字
# global 变量
# nonlocal 变量

 

2.3 迭代器/生成器相关(3)

  range(),next(),iter()

#迭代器.__next__()
# next(迭代器)
迭代器 = iter(可迭代的)
迭代器 = 可迭代的.__iter__()

range(10)
range(1,11)
print('__next__' in dir(range(1,11,2)))

2.4 反射相关(4)

  hasattr(),getattr(),setattr(),delattr()

2.5 面向对象相关(9)

待补充

2.6 其他(12)

  1,字符串类型代码执行

    eval(),exec(),complie()

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

    exec():执行字符串类型的代码

    complie():将一个字符串编译为字节代码。

# exec('print(123)')
# eval('print(123)')
# print(eval('1+2+3+4'))   # 有返回值
# print(exec('1+2+3+4'))   #没有返回值
# exec和eval都可以执行 字符串类型的代码
# eval有返回值  —— 有结果的简单计算
# exec没有返回值   —— 简单流程控制
# eval只能用在你明确知道你要执行的代码是什么

# code = '''for i in range(10):
#     print(i*'*')
# '''
# exec(code)

# code1 = 'for i in range(0,10): print (i)'
# compile1 = compile(code1,'','exec')
# exec(compile1)

# code2 = '1 + 2 + 3 + 4'
# compile2 = compile(code2,'','eval')
# print(eval(compile2))

# code3 = 'name = input("please input your name:")'
# compile3 = compile(code3,'','single')
# exec(compile3) #执行时显示交互命令,提示输入
# print(name)
# name #执行后name变量有值
# "'pythoner'"
View Code

  2,输入输出(2)

    input()

    print()

ret = input('提示 : ')
print(ret)

print('我们的祖国是花园',end='')  #指定输出的结束符
print('我们的祖国是花园',end='')
print(1,2,3,4,5,sep='|') #指定输出多个值之间的分隔符
f = open('file','w')
print('aaaa',file=f)
f.close()
View Code

 例子: 打印进度条

for i in range(0,101,2):
     time.sleep(0.1)
     char_num = i//2
     per_str = '\r%s%% : %s\n' % (i, '*' * char_num) \
         if i == 100 else '\r%s%% : %s' % (i,'*'*char_num)
     print(per_str,end='', flush=True)

progress Bar # 打印进度条的模块
打印进度条

  3,内存相关(2)

    hash()

    id()

#id
#hash - 对于相同可hash数据的hash值在一次程序的执行过程中总是不变的
#     - 字典的寻址方式
print(hash(12345))  # ==>12345
print(hash('hsgda不想你走,nklgkds')) # ==>1522337460713999777
print(hash(('1','aaa')))  #==> 8240687158609221215
print(hash([]))  # ==>TypeError: unhashable type: 'list'
View Code

  4,文件操作相关

    open()

# f = open('1.复习.py')
print(f.writable())
print(f.readable())
open()

  5,模块相关

    __import__

# import time
t = __import__('time')
print(t.time())  # ==>1598306841.6678045
__import__

  6,帮助相关

    help()

# help
help(str)

class str(object)
 |  str(object='') -> str
 |  str(bytes_or_buffer[, encoding[, errors]]) -> str
 |  
 |  Create a new string object from the given object. If encoding or
 |  errors is specified, then the object must expose a data buffer
 |  that will be decoded using the given encoding and error handler.
 |  Otherwise, returns the result of object.__str__() (if defined)
 |  or repr(object).
 |  encoding defaults to sys.getdefaultencoding().
 |  errors defaults to 'strict'.
 |  
 |  Methods defined here:
 |  
 |  __add__(self, value, /)
 |      Return self+value.
 |  
 |  __contains__(self, key, /)
 |      Return key in self.
 |  
 |  __eq__(self, value, /)
 |      Return self==value.
 |  
 |  __format__(self, format_spec, /)
 |      Return a formatted version of the string as described by format_spec.
 |  
 |  __ge__(self, value, /)
 |      Return self>=value.
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __getitem__(self, key, /)
 |      Return self[key].
 |  
 |  __getnewargs__(...)
 |  
 |  __gt__(self, value, /)
 |      Return self>value.
 ...
'''
help

  7,调用相关

    callable()

# 变量
print(callable(print))  # ==>True
a = 1
print(callable(a))   # ==>False
print(callable(globals))  # ==>True
def func():pass
print(callable(func))   # ==>True
callable

  8,查看内置属性

    dir()

# dir 查看一个变量拥有的方法
print(dir([]))
print(dir(1))

'''
['__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']
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
'''
dir

 

posted @ 2020-08-22 06:40  勇敢面对difficult  阅读(104)  评论(0)    收藏  举报