python - 函数
函数的定义和常用操作
- 函数:对程序逻辑进行结构化的一种变成方法
- 函数的定义:
def 函数名称:
代码
return 需要返回的内容
- 函数的调用:
函数名称()
- 练习
# 读取人物名称
f = open('names.txt')
data = f.read()
print (data.split('|'))
# 读取刀器名称
f2 = open('weapon.txt')
# data2 = f2.read()
i = 1
for line in f2.readlines():
if i % 2 == 1:
print (line.strip('\n'))
i += 1
f3 = open('sanguo.txt')
print (f3.read().replace('\n', ''))
import re
def find_item(hero):
with open('sanguo.txt') as f:
data = f.read().replace('\n', '')
name_num = re.findall(hero, data)
#print ('主角 %s 出现 %s 次' %(hero, len(name_num)))
return len(name_num)
# 读取人物的信息
name_dict = {}
with open('names.txt') as f :
for line in f:
names = line.split('|')
for n in names:
name_num = find_item(n)
name_dict[n] = name_num
name_sorted = sorted(name_dict.items(), key=lambda item : item[1], reverse=True)
print (name_sorted[0:10])
函数的可变长参数
- 定义:带* 的参数是可以随机传入的参数
- 练习
# 获得参数的个数
def howLong(first, *other):
print (1 + len(other))
howLong(123, 234, 456)
函数的变量作用域
- global 加关键字,让var1成为全局变量,练习1 :在var1=‘456’只作用在局部变量内,
- 练习
var1 = 123
def func() :
var1 = '456'
print (var1)
func()
print (var1)
var1 = 123
def func() :
global var1
var1 = '456'
print (var1)
func()
print (var1)
函数的迭代器与生成器
- yield是生成器,也是迭代器的一种,当需要自己构建迭代器的时候。可以使用这个关键字。
- 练习
def frange(start, stop, step):
x = start
while x < stop:
yield x
x += step
for i in frange(10, 20, 0.5):
print (i)
Lambda表达式
>>> def add(x,y):
... return x+y
...
def add(x,y) : return x+y
lambda x,y : return x+y
>>> def fun(item):
... return item[1]
...
>>> adict = {'a':'aa','b':'bb'}
>>> for i in adict.items():
... fun(i)
...
'aa'
'bb'
python 的内建函数
-
有iter()方法的 都可以使用for in 的形式
-
filter() map() reduce() zip()
-
filter()
a = [1,2,3,4,5,6,7,8]
list(filter(lambda x : x >2, a))
- map()
a = [1,2,3]
list(map(lambda x : x, a))
list(map(lambda x : x +1, a))
b = [4,5,6]
list(map(lambda x,y : x+y, a,b))
- reduce():使用reduce之前需要引入from functools import reduce
from functools import reduce
reduce (lambda x,y: x+y, [2,3,4],1)
10
- zip()
zip((1,2,3), (4,5,6))
for i in zip((1,2,3), (4,5,6)):
print(i)
dicta = {'a':'aa', 'b':'bb'}
dictb = zip(dicta.values(), dicta.keys())
print(dict(dictb))
{'aa': 'a', 'bb': 'b'}
闭包的定义
- 定义:外部函数被内部函数引用,叫做闭包
- 练习
# sum() 是外部函数,add() 是内部函数
def sum(a):
def add(b):
return a + b
return add
def func():
a = 1
b = 2
return a + b
# sum() 是外部函数,add() 是内部函数
def sum(a):
def add(b):
return a + b
return add
# add 函数名称或者函数的引用
# add() 函数的调用
num1 = func()
num2 = sum(2)
print (num2(4))
print (type(num1))
print (type(num2))
- 闭包实现计数器的功能
计数每调用一次加1
def counter():
cnt = [0]
def add_one():
cnt[0] += 1
return cnt[0]
return add_one
num1 = counter()
print (num1())
print (num1())
print (num1())
print (num1())
print (num1())
print (num1())
计数调用
def counter(FIRST=0):
cnt = [FIRST]
def add_one():
cnt[0] += 1
return cnt[0]
return add_one
num5 = counter(5)
num10 = counter(10)
print (num5())
print (num5())
print (num5())
print (num5())
print (num10())
print (num10())
闭包的使用
- 练习
def a_line(a, b):
def arg_y(x):
return a * x +b
return arg_y
# 代码简介后:
def a_line(a, b):
return lambda x : a * x + b
line1 = a_line(3, 5)
line2 = a_line(5, 10)
print (line1(10))
print (line1(20))
print (line2(10))
print (line2(20))
装饰器的定义
import time
print (time.time())
time.sleep(3)
def i_can_sleep():
time.sleep(3)
start_time = time.time()
i_can_sleep()
end_time = time.time()
print ('函数执行时间 %s 秒' % (end_time - start_time))
# 装饰器 @timmer
def timmer(func):
def wrapper():
start_time = time.time()
func()
stop_time = time.time()
print ('运行时间是 %s 秒' %(stop_time - start_time))
return wrapper
@timmer
def i_can_sleep():
time.sleep(3)
i_can_sleep()
timmer(i_can_sleep())
# 装饰器执行过程
num = timmer(i_can_sleep())
num()
装饰器的使用
def new_tips(argv):
def tips(func):
def nei(a, b):
print ('start %s' %argv)
func(a, b)
print ('stop %s' %argv)
return nei
return tips
@new_tips('add')
def add(a, b):
print (a + b)
@new_tips('sub')
def sub(a,b):
print (a - b)
add(1, 2)
sub(1, 2)
def new_tips(argv):
def tips(func):
def nei(a, b):
print ('start %s %s' %(argv, func.__name__)) # __name__ 获取函数名字
func(a, b)
print ('stop %s' %argv)
return nei
return tips
@new_tips('add')
def add(a, b):
print (a + b)
@new_tips('sub')
def sub(a,b):
print (a - b)
add(1, 2)
sub(1, 2)
自定义上下文管理器
fd = open('name.txt')
try:
for line in fd:
print (line)
finally:
fd.close()
with open('name.txt') as f:
for line in f:
print (line)