day16

作用域:
name='alex'
def foo():
  name='linhaifeng'
  def bar():
    print(name)
foo()

def test():
  pass
print(test)


def test1():
  print('in the test1')
def test():
  print('in the test')
  return test1
print(test)
res=test()
print(res)

#结果
<function test at 0x00454A98>
in the test
<function test1 at 0x004307C8>

def test1():
  print('in the test1')
def test():
  print('in the test')
  return test1
print(test)
res=test()
print(res())
#结果
in the test
in the test1
None

name='alex'
def foo():
  name='linhaifeng'
  def bar():
    name='wupeiqi'
    print(name)
  return bar
a=foo()
print(a)
print(a())

#结果

<function foo.<locals>.bar at 0x011D4A98>

wupeiqi
None


name='alex'
def foo():
  name='lhf'
  def bar():
    name='wupeiqi'
    def tt():
      print(name)
    return tt
  return bar

bar=foo()
tt=bar()
res=tt()
print(res)

#结果
wupeiqi
None


匿名函数
lambda x:x+1   #lambda 形参:返回值

def calc(x):
  return x+1

res=calc(10)
print(10)


func=lambda x:x+1
print(func(10))


name='alex'   #name='alex_sb'

def change(name):
  return name+'_sb'
res=change(name)
print(res)

func=lambda name:name+'_sb'
  print(func(name))

lambda x,y,z:(x+1,y+1,z+1)

函数式编程

编程的方法论:
面向过程
函数式
编程语言定义的函数+数学意义的函数
y=2*x+1

def calc(x):
  return 2*x+1

面向对象

例一:不可变:不用变量保存状态,不修改变量
#非函数式
a=1
def incr_test1():
  global a
  a+=1
  return a
incr_test1()
print(a)

#函数式
n=1
def incr_test2():
  return n+1
incr_test2()
print(n)

例二:第一类对象:函数即“变量”
函数名可以当参数传递
返回值可以是函数名
#高阶函数:满足下面两个条件之 一1、函数接收的参数是函数名 2、返回值包含函数
#把函数当参数传给另一个函数
def foo(n):
  print(n)

def bar(name):
  print('my name is %s' %name)

foo(bar)
foo(bar('alex')

#返回值包含函数
def bar():
  print('from bar')
def foo()
  print('from foo')
  return bar
n=foo()
n()

def handle():
  print('from handle')
  return handle
h=handle()
h()

def test1():
  print('from test1')
def test2():
  print('from handle')
  return test1()

例三:
尾调用:在函数的最后一步调用另外一个函数(最后一行不一定是函数的最后一步)
#函数bar在foo内卫尾调用
def bar(n):
  return n
def foo():
  return bar(x)
#最后一行不一定是最后一步
#函数bar在foo内非尾部调用
def bar(n):
  return n
def foo(x):
  return bar(x)+1



#最后一步不一定是函数的最后一行
def test(x):
  if x>1:
    return True
  elif x==1:
    return False
  else:
    return 'a'
test(1)

非尾递归
def cal(seq):
  if len(seq)==1:
    return seq[0]
  head,*tail=seq
  return head+cal(tail)
print(cal(range(100)))

尾递归
def cal(l):
  print(l)
  if len(l)==1:
    return l[0]
  first,second,*args=1
  l[0]=first+second
  l.pop(1)
  return cal(l)
x=cal([i for in range(10)])
print(x)


num=[1,2,10,5,3,7]
ret=[]
for i in num:
  ret.append(i**2)
print(ret)


def map_test(array):
  ret=[]
  for i in arry:
    ret.append(i**2)
  print(ret)
  return ret
ret=map_test(num)
print(ret)


def add_one(x):
  return x+1 #lambda x:x+1
def reduce_one(x):
  return x-1
def cf(x):
  x**2


def map_test(fun,array):
  ret=[]
  for i in arry:
    n=fun(i)
    ret.append(n)
  print(ret)
  return ret

map_test(add_one,num) #map_test(lambda x:x+1,num)

#map函数 map(函数或lambda,可迭代对象)
map(lambda x:x+1,num)


movie_peoples=['sb_alex','sb_wupeiqi','linhaifeng','sb_yuanhao']
ret=[]
for p in movie_peoples:
  if not p.startswith('sb'):
    ret.append(p)
print(ret)

movie_peoples=['sb_alex','sb_wupeiqi','linhaifeng','sb_yuanhao']
def filter_test(array):
  ret=[]
  for p in array:
    if not p.startswith('sb'):
      ret.append(p)
      return ret
ret=filter_test(movie_people)
print(ret)


def sb_show(n):
  return n.endswith('sb')
def filter_test(fun,array):
  ret=[]
  for p in array:
    if not fun(p):
      ret.append(p)
      return ret
ret=filter_test(sb_show,movie_people)
print(ret)


#终极版本
def filter_test(fun,array):
  ret=[]
  for p in array:
    if not fun(p):
      ret.append(p)
      return ret
ret=filter_test(lambda n:n.endswith('sb'),movie_people)
print(ret)


#filter函数
filter(函数,可迭代对象)

movie_peoples=['sb_alex','sb_wupeiqi','linhaifeng','sb_yuanhao']
res=list(filter(lambda n:not n.startswith('sb'),movie_peoples))
print(res)


#from functools import reduce
num=[1,2,3,4,5,6,100]
res=0
for n in num:
  res+=n
print(res)

def reduce_test(array):
  res=0
  for n in array:
    res+=n
  return res
res=reduce_test(num)
print(res)


def multi(x,y):
  return x*y

lambda x,y:x*y

def reduce_test(func,array):
  res=array.pop(0)
  for n in array:
    res=fun(n,res)
  return res
res=reduce_test(lambda x,y:x*y,num)
print(res)


def reduce_test(func,array,init=None):
  if init==None:
    res=array.pop(0)
  else:
    res=init
  for n in array:
    res=fun(n,res)
  return res
res=reduce_test(lambda x,y:x*y,num,100)
print(res)

#reduce函数
from functools inmport reduce
num=[1,2,3,100]
print(reduce(lambda x,y:x+y,num,1)) #reduce(函数,可迭代对象,指定值)


小结
#处理序列中的每个元素,得到一个列表,该列表元素个数及位置与原来一样
map()


#遍历序列中的每一个元素,判断每个元素的布尔值,如果是True则留下来,
filter()

people=[
  {'name':'alex','age':1000},
  {'name':'wupeiqi','age':10000},
  {'name':'yuanhao','age':9000},
  {'name':'linhaifeng','age':18}
]


print(list(filter(lambda n:n['age']<100,people)))


#处理一个序列,然后把序列进行合并操作
reduce()

内置函数
print(abs(-1))

print(all([1,2,'1'])) #布尔运算(与)
print(all('1230')) #把字符串当成整体

print(any([])) #(或)

print(bin(3)) #转成二进制

print(bool('')) #判断布尔值
#空,None,0的布尔值为False ,其余为True
print((0))
print((''))
print((None))

name='你好'
print(bytes(name,encoding='utf-8')) #以二进制形式进行编码
print(bytes(name,encoding='utf-8').decode=('utf-8'))
#结果
b'xe4xbdxa0xe5xa5xbd'
你好

print(chr(97)) #以ascii进行编码

print(dir(all)) #打印某个对象下面有哪些方法
print(dir(dict))

print(divmod(10,3)) #做商 可做分页功能
#结果
(3,1)

把字符串中的数据结构给提取出来
dic={'name':'alex'}
dic_str=str(dic)
print(dic_str) #结果 '{'name':'alex'}'
eval(dic_str) #结果{'name':'alex'}
把字符串中的表达式进行运算
express='1+2*(3/3-1)-2'
eval(express)

#可hash的数据类型即不可变数据类型,
print(hash('123123123'))

print(help(all)) #查看如何使用

print(hex(12)) #十进制转十六进制
print(oct(12)) #十进制转八进制
bin() #十进制转二进制

print(isinstance(1,int)) #判断1是不是int

name='zhouhaocheng'
print(gloabals()) #全局变量
print(locals()) #局部变量

l=[1,3,100,-1,2]
print(max(l)) #min() 取最大最小值

 2018-08-19

原文地址:https://www.cnblogs.com/jiangjunfeng/p/9500338.html