函数-内置方法
abs() 绝对值
dict() 字典
help() 帮助
min() /max() 取最小/大值
setattr()
all()
bool()
any()
dir() 打印对当前程序的所有变量
hex() 16进制
slice() 切片
divmod() 取整除
sorted() 自定义排序的规则
ascii()
a =[1,2,3,4]
all(a)
True
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'a']
s=slice[1,7,2]
>>> help(divmod)
Help on built-in function divmod in module builtins:
divmod(x, y, /)
Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
>>> divmod(10,3)
(3, 1)
>>>
>>> l=list(range(10))
>>>
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> l[4]=99
>>> sorted(l)
[0, 1, 2, 3, 5, 6, 7, 8, 9, 99]
>>>
d={}
for i in range(20):
d[i]=i-50
print(d)
>>{0: -50, 1: -49, 2: -48, 3: -47, 4: -46, 5: -45, 6: -44, 7: -43, 8: -42, 9: -41, 10: -40, 11: -39, 12: -38, 13: -37, 14: -36, 15: -35, 16: -34, 17: -33, 18: -32, 19: -31}
>>>> d.items()
dict_items([(0, -50), (1, -49), (2, -48), (3, -47), (4, -46), (5, -45), (6, -44), (7, -43), (8, -42), (9, -41), (10, -40), (11, -39), (12, -38), (13, -37), (14, -36), (15, -35), (16, -34), (17, -33), (18, -32), (19, -31)])
>>> sorted(d.items())
[(0, -50), (1, -49), (2, -48), (3, -47), (4, -46), (5, -45), (6, -44), (7, -43), (8, -42), (9, -41), (10, -40), (11, -39), (12, -38), (13, -37), (14, -36), (15, -35), (16, -34), (17, -33), (18, -32), (19, -31)]
>>> sorted(d.items(),key=lambda x:x[1],reverse=True)
[(19, -31), (18, -32), (17, -33), (16, -34), (15, -35), (14, -36), (13, -37), (12, -38), (11, -39), (10, -40), (9, -41), (8, -42), (7, -43), (6, -44), (5, -45), (4, -46), (3, -47), (2, -48), (1, -49), (0, -50)]
>>> a ='lll路飞'
>>> ascii(a)
"'lll\\u8def\\u98de'"
>>>
eval() 按解释器的规则字符串转代码(只能处理单行代码)
exec() 可执行多行代码
>>> f='1+2/3'
>>> f
'1+2/3'
>>> eval(f)
1.6666666666666665
>>>
>>>> code='''
... if 4>9:
... print('4>9')
... else:
... print('d')
... '''
>>> exec(code)
d
>>>
code ='''
def foo():
print('run foo')
return 1234
foo()
'''
a = eval('1+2+3')
# a = exec('1+2+3')
# res = exec(code)
print(a)
ord()
chr()
>>> ord('a')
97
>>> chr(97)
'a'
sum() 求和
>>> a=[1,2,3,4]
>>> sum(a)
10
>>>
bytearray()
>>> s
'abclfkfkfkf开发'
>>> s=s.encode('utf-8')
>>>> s
b'abclfkfkfkf\xe5\xbc\x80\xe5\x8f\x91'
>>> s=bytearray(s)
>>> s
bytearray(b'abclfkfkfkf\xe5\xbc\x80\xe5\x8f\x91')
>>> s[0]
97
>>> s[0]=65
>>> s
bytearray(b'Abclfkfkfkf\xe5\xbc\x80\xe5\x8f\x91')
>>> s[4]
102
>>> s[4]=103
>>> s
bytearray(b'Abclgkfkfkf\xe5\xbc\x80\xe5\x8f\x91')
>>> s.decode()
'Abclgkfkfkf开发'
>>> id(s)
2555799282384
>>> s
bytearray(b'Abclgkfkfkf\xe5\xbc\x80\xe5\x8f\x91')
>>> s[0]=67
>>> id(s)
2555799282384 #内存地址不变
map()
filter() 用法同map一样 结果不一样
reduce()
>>> map(lambda x:x*x,[1,2,3,4,5])
<map object at 0x0000025311822278>
>>> list( map(lambda x:x*x,[1,2,3,4,5]))
[1, 4, 9, 16, 25]
>>> filter(lambda x:x>3,[1,2,3,4,5])
<filter object at 0x00000253118221D0>
>>> list(filter(lambda x:x>3,[1,2,3,4,5]))
[4, 5]
>>> import functools
>>>
>>> functools.reduce(lambda x,y:x+y,[1,2,3,4,5])
15
>>> functools.reduce(lambda x,y:x*y,[1,2,3,4,5])
120
pow()
>>> help(pow)
Help on built-in function pow in module builtins:
pow(x, y, z=None, /)
Equivalent to x**y (with two arguments) or x**y % z (with three arguments)
Some types, such as ints, are able to use a more efficient algorithm when
invoked using the three argument form.
>>>
print()
>>> help(print)
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
>>>
>>>> print('hai','ff',sep='|')
hai|ff
>>>
>>>> a='help ,sos\n'
>>> print(a)
help ,sos
>>> print(a,end='|')
help ,sos
|>>>
callable() 判断一个东西是否可调用
>>> print('hai','ff',sep='|')
hai|ff
>>> help(callable)
Help on built-in function callable in module builtins:
callable(obj, /)
Return whether the object is callable (i.e., some kind of function).
Note that classes are callable, as are instances of classes with a
__call__() method.
>>>>>> def f():
... pass
...
>>>
>>> f
<function f at 0x0000025311B1E1E0>
>>> callable(f)
True
>>>>>> a=[1,2,3,4,6,7]
>>> callable(a)
False
frozenst()
不可变集合
>>> s={1,2,3,45,5,6,6,}
>>> s
{1, 2, 3, 5, 6, 45}
>>> s.discard(1)
>>> s
{2, 3, 5, 6, 45}
>>> s=frozenset()
>>> s
frozenset()
locals()
>>> def f():
... n=3
... print(locals())
...
>>> f()
{'n': 3}
>>>
>>> locals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'd': {0: -50, 1: -49, 2: -48, 3: -47, 4: -46, 5: -45, 6: -44, 7: -43, 8: -42, 9: -41, 10: -40, 11: -39, 12: -38, 13: -37, 14: -36, 15: -35, 16: -34, 17: -33, 18: -32, 19: -31}, 'a': 'help ,sos\n', 'l': [0, 1, 2, 3, 5, 6, 7, 8, 9, 99], 'f': '1+2/3', 'code': "\nif 4>9:\n print('4>9')\nelse:\n print('d')\n", 'c': '\nif \n\n', 's': bytearray(b'Cbclgkfkfkf\xe5\xbc\x80\xe5\x8f\x91'), 'functools': <module 'functools' from 'E:\\Python37\\lib\\functools.py'>}
>>> vars()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'd': {0: -50, 1: -49, 2: -48, 3: -47, 4: -46, 5: -45, 6: -44, 7: -43, 8: -42, 9: -41, 10: -40, 11: -39, 12: -38, 13: -37, 14: -36, 15: -35, 16: -34, 17: -33, 18: -32, 19: -31}, 'a': 'help ,sos\n', 'l': [0, 1, 2, 3, 5, 6, 7, 8, 9, 99], 'f': '1+2/3', 'code': "\nif 4>9:\n print('4>9')\nelse:\n print('d')\n", 'c': '\nif \n\n', 's': bytearray(b'Cbclgkfkfkf\xe5\xbc\x80\xe5\x8f\x91'), 'functools': <module 'functools' from 'E:\\Python37\\lib\\functools.py'>}
global() 全局变量
tuple() 元组
repr()
>>> a =[1,3]
>>> repr(a)
'[1, 3]'
zip()
>>> a=[1,2,3,4]
>>> b=['a','b','v']
>>> zip(a)
<zip object at 0x0000025311B6AE88>
>>> list(zip(a,b))
[(1, 'a'), (2, 'b'), (3, 'v')]
>>>
compile()
complex()
round()
hash() 把字符串变成数字
set() 把列表变成集合
delattr,hasattr,getattr,setattr
>>> complex(3,5)
(3+5j)
>>>>>> round(1.33333344,4)
1.3333
>>>
>>>> hash('abc')
-4344963955325051630
>>>>>> set([1,23,4])
{1, 4, 23}
>>>>>> delattr,hasattr,getattr,setattr
(<built-in function delattr>, <built-in function hasattr>, <built-in function getattr>, <built-in function setattr>)
>>>
命名空间
名称空间 又名name space 顾名思义就是存放名字的地方,举例说明:若变量x=1,1存放于内存中,是存放名字x与1绑定关系的地方
名称空间3种
locals:函数内的名称空间,包括局部变量和形参
globals:全局变量
builtins:内置模块的名字空间
不同变量的作用域不同就是由这个变量所在的命名空间决定的
>>> x=1
>>> globals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'x': 1}
>>>
>>>> locals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'x': 1}
>>>>>> __builtins__
<module 'builtins' (built-in)>
>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '_', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
>>>
作用域范围
全局范围:全局存活,全局有效
局部范围:临时存活,局部有效
查看作用域方法:globals(),locals()
作用域的查找空间
n=10
def func():
n=20
print("func",n)
def func2():
n=30
print("func2",n)
def func3():
print("func3",n)
func3()
func2()
func()
#输出结果
func 20
func2 30
func3 30
闭包
def func():
n=10
def func2():
print("func2",n)
return func2
f=func()
print(f)
f()
#输出结果
<function func.<locals>.func2 at 0x000001891968DA60>
func2 10
闭包(closure)是函数式编程的重要的语法结构。函数式编程是一种编程范式 (而面向过程编程和面向对象编程也都是编程范式)。在面向过程编程中,我们见到过函数(function);在面向对象编程中,我们见过对象(object)。函数和对象的根本目的是以某种逻辑方式组织代码,并提高代码的可重复使用性(reusability)。闭包也是一种组织代码的结构,它同样提高了代码的可重复使用性。
装饰器
封闭:已实现的功能代码块不应该被修改
开放:对现有功能的拓展开放
装饰器流程分析
user_status = False
def login(func4): #func2
def inner():
user_name = 'alex'
user_password = 'abc123'
global user_status
if user_status == False:
name = input("请输入登录名:")
password = input("请输入密码:")
if name==user_name and password==user_password:
print("登陆成功....")
user_status= True
elif name !=user_name:
print("用户名错误")
elif password != user_password:
print("密码错误")
else:
print("用户名密码不存在")
else:
print("用户已登陆,验证通过")
if user_status:
func4() #func2
return inner
def func1():
print("-----首页------")
@login
def func2():
print("------内地剧场------")
def func3():
print("-----国外--------")
# func2 = login(func2) #inner 相当于@login
# print(func2)
func2()
装饰带参数的函数
user_status = False
def login(func4): #func2
def inner(*arg,**kwargs): #mm ww
user_name = 'alex'
user_password = 'abc123'
global user_status
if user_status == False:
name = input("请输入登录名:")
password = input("请输入密码:")
if name==user_name and password==user_password:
print("登陆成功....")
user_status= True
elif name !=user_name:
print("用户名错误")
elif password != user_password:
print("密码错误")
else:
print("用户名密码不存在")
else:
print("用户已登陆,验证通过")
if user_status:
func4(*arg,**kwargs) #func2
return inner
def func1():
print("-----首页------")
@login
def func2(style):
print("------内地剧场------",style)
@login
def func3():
print("-----国外剧场--------")
# func2 = login(func2) #inner 相当于@login
# print(func2)
func2('mm')
func3()
装饰器带参数
user_status = False
def login(func4): #func2
def outer(func5):
def inner(*arg,**kwargs): #mm
user_name = 'alex'
user_password = 'abc123'
global user_status
if user_status == False:
name = input("请输入登录名:")
password = input("请输入密码:")
if name==user_name and password==user_password:
print("登陆成功....")
user_status= True
elif name !=user_name:
print("用户名错误")
elif password != user_password:
print("密码错误")
else:
print("用户名密码不存在")
else:
print("用户已登陆,验证通过")
if user_status:
func5(*arg,**kwargs) #func2
return inner
return outer
def func1():
print("-----首页------")
@login('wx') #xx lonin('wx') 返回outer 相当于(func2)=inner
def func2(style):
print("------内地剧场------",style)
@login('qq')
def func3():
print("-----国外剧场--------")
# func2 = login(func2) #inner 相当于@login
# print(func2)
# xx = login(func2)
# print(xx)
# func2 = xx(func2)
# print(func2)
func2('mm')
列表生成式
a = [1,2,3,4,5,6]
for index ,i in enumerate(a):
a[index]+=1
print(a)
b = [i+1 for i in range(10)]
print(b)
c= [i*i for i in range(10)]
print(c)
d=[i if i<5 else i*i for i in range(10)]
print(d)
e ='alex'
e=[i for i in e]
print(e)
[2, 3, 4, 5, 6, 7]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[0, 1, 2, 3, 4, 25, 36, 49, 64, 81]
['a', 'l', 'e', 'x']
生成器
>>> a=(i for i in range(100))
>>> a
<generator object <genexpr> at 0x0000021DB0823C78>
>>>
>>> next(a)
0
>>> next(a)
1
>>> next(a)
2
>>> next(a)
3
>>> next(a)
4
>>> next(a)
5
>>>>>> b=(i for i in range(3))
>>> b
<generator object <genexpr> at 0x0000021DB244B318>
>>> next(b)
0
>>> next(b)
1
>>> next(b)
2
>>> next(b) #超出范围会报错,只有next方法
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>>
>>> a,b=1,2
>>> a
1
>>> b
2
>>> a,b=b,a+b
>>> a,b
(2, 3)
>>> t=a
>>> t
1
>>> a,b=b,t+b
>>> a,b
(2, 3)
>>> a =(i for i in range(5))
>>>#for i in a:
>>> # print(i)
>>> while True:
... next(a)
...
0
1
2
3
4
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
StopIteration
>>>
斐波那契数列
除第一个和第二个数之外,任意一个数可由前两个数相加
def fib(max):
n,a,b=0,0,1
while n<max:
print("before yield")
yield b #把函数的执行过程冻结在这一步,并且把b的值返回给外面的next()
print(b)
a,b=a,a+b
n=n+1
return 'done'
f=fib(15) #turn function into generator
next(f) #first time call next()
next(f) #first time call next()
#结果
before yield
1
before yield
生成器调用方法
range 是个生成器
python2
range =list
xrange =生成器
python3
range = 生成器
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>>>> a=(i for i in range(4))
>>> for i in a:
... print(i)
...
0
1
2
3
函数写生成器
生成器的创建方式
1.列表生成式 (最复杂的:三元运算)
2.函数
def range2(n):
count =0
while count< n:
print('count',count)
count +=1
print("before yield")
yield count # return
f=range2(10)
r1=next(f)
print(r1)
r2=next(f)
print(r2)
#返回结果
count 0
before yield
count 1
before yield
yield vs return
return 返回并终止function
yield 返回 数据,并冻结当前执行过程
next 唤醒冻结的执行过程 ,继续执行,知道遇到下一个yield
函数有了yield之后
1.函数名加()变成了生成器
2.return 在生成器里 代表生成器的终止,直接报错
生成器send方法
next
唤醒并继续执行
send
1.唤醒并继续执行
2.发送一个信息到生成器 内部
def range2(n):
count =0
while count< n:
print('count',count)
count +=1
sign= yield count # return
if sign == "stop":
print("-sign",sign)
break
return 333
f=range2(3)
r1=next(f)
f.send(None)
迭代器
迭代 =循环
直接作用于for循环的数据类型:
一类 集合数据类型 如list tuple dict set str
一类 generator 包括生成器 和带yield 的generator function
Iteratable
可以被next() 函数调用并不断返回下一个值的对象成为迭代器:Iterator
>>> from collections import Iterator
>>>> isinstance((x for x in range(10)),Iterator)
True
>>>> a=iter('abc')
>>>
>>> a
<str_iterator object at 0x000001732BF510F0>
>>>
生成器都是Iterator对象,但list dict str 虽然是Iterable,却不是 Iterator
把list dict str 等 Iterable 变成 Iterator 可以使用函数 iter()
Iterator 在python里表示的是数据流 可以表示无线大的数据流
而使用list 是永远不可能存储全体自然数的
小结:
凡是可作用于for 循环的对象都是Iterable 类型
凡是可作用于next() 函数的对象都是Iterator 类型,它们表示一个惰性计算的序列
集合数据类型如list dict str 等都是Iterable,但不是Iterator ,不过可以通过iter() 函数获得一个Iterator 对象
python3的for 循环本质上就是通过不断调用next () 函数实现的