python基础语法四

时间:2024-01-18 16:52:14

函数的作用域:

 name = 'alex'

     def foo():
name = 'linhaifei'
def bar():
name = "wupeiqi"
def tt():
name='tt'
print(name)
return tt
return bar foo()()()

#匿名函数

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

  

name =  'alex' #name = 'alex'
函数:
def chang_name(x):
 return name+'_sb'
匿名函数: 
lambda x:name+'_sb'
函数式编程:函数式 = 编程语言定义的函数+ 数学意义上的函数
 编程的方法论:
  面向过程
  函数式
  面向对象
  
 高阶函数:
  满足两个特性任意一个即为高阶函数
  1.函数的传入参数是一个函数名
  2.函数的返回值是一个函数名
 def bar():
print("from bar") def foo():
print('from foo')
return bar
n = foo()
n() #尾递归:
def cal(l):
print("assd")
return cal(l)

map 函数:

num_l = [1, 2, 3, 4, 5]
def map_test(func, array): #func = lambda x:x+1 array = [1, 2, 3, 4, 5]
ret = []
for i in array:
res = func(i)
ret.append(res)
return ret print(map_test(lambda x:x+1, num_l) res = map(lambda x:x+1, num_l)
#for i in res:#迭代器,只能迭代一次!
# print(i)
print(list(res))

  
filter函数:

movie_people = ['sb_alex', 'sb_wupeiqi', 'linhaifeng', 'sb_yuanhao']

def sb_show(n):
return n.endswith('sb')
# lambda n: n.endswith('sb') def filter_test(func,array):
ret = []
for i in array:
if not i.func(i):
ret.append(i)
return ret
print(filter_test(sb_show, movie_people)) #最终:
filter(lambda n:not n.endswith('sb'), movie_people)
print(list(filter(lambda n:not n.endswith('sb'), movie_people)))

  reduce 函数:

num_l = [1, 2, 3, 4, 5]
#相加:
#res = 0
#for num in num_l:
# res+=num
#print(res) def multi(x, y):
return x*y def reduce_test(func, array, init=None):
if init is None:
res = array.pop(0)
else:
res = init
for num in array:
res=func(res, num)
return res #最终:
from function import reduce
num_l=[1, 2, 3, 100]
print(reduce(lambda x, y:x+y, num_l, 1)

  文件处理:

    f = open('文件名', encoding='utf-8')
data = f.read()
print(data)
f.close() #r w a
默认打开的就是只读模式
f = open('文件名','r', encoding='utf-8')
data = f.read()
print(f.readable())
print(f.readline())
print(data)
f.close() #w 模式: 如果文件存在,文件会被清除,如果文件不存在,文件会被新建
f = open('文件名','w', encoding='utf-8')
f.write('111111\n')
f.write('222222\n')
#f.writeable()#是否可写
#f.writelines(['555\n', '666\n'])
f.close()
#a 可追加
f = open('文件名','a', encoding='utf-8')
f.write('111111\n') f.close() 即能读,也能写
f = open('文件名','r+', encoding='utf-8')
data = f.read()
print(f.readable())
print(f.readline())
print(data)
f.close()