函数学习要点:
1、函数基本操作:调用、创建、可变长参数(在方法定义中可以使用个数不确定的参数,不按顺序传参用关键字,不固定参数个数定义为fun(first,*other))、变量作用域
2、匿名函数(Lambda函数)
3、函数迭代器、生成器
4、函数闭包、装饰器
5、内建函数
6、自定义上下文管理器
实践操作代码:
未使用函数时代码
# 读取人物名称,name.txt是创建在代码路径下人物txt文档
f = open('name.txt',encoding='utf-8')
data = f.read()
data0 = data.split('|')
print(type(data))
print(data0)
# 读取兵器名称,weapon.txt是创建在代码路径下兵器txt文档
f2 = open('weapon.txt',encoding='utf-8')
i = 1
for line in f2.readlines():
if i % 2 == 1:
print(line.strip('\n'))
i += 1
# 去掉文件中每行文字换行,sanguo_utf8.txt是创建在代码路径下文章txt文档
f3 = open('sanguo_utf8.txt',encoding='utf-8')
print(f3.read().replace('\n',''))
上面功能用函数实现代码
def func(filename):
print(open(filename,encoding='utf-8').read())
print('test func')
func('name.txt')
用函数实现统计人物和武器出现次数例子
import re
def find_main_charecters(charecter_name):
with open('sanguo_utf8.txt', encoding='utf-8') as f:
data = f.read().replace("\n", "")
name_num = re.findall(charecter_name, data)
# print('主角 %s 出现了%s 次'%(charecter_name,len(name_num)))
return charecter_name, len(name_num)
name_dict = {}
with open('name.txt', encoding='utf-8') as f:
for line in f:
names = line.split('|')
for n in names:
char_name, char_number = find_main_charecters(n)
name_dict[char_name] = char_number
weapon_dict = {}
with open('weapon.txt', encoding='utf-8') as f:
i = 1
for line in f:
if i%2 == 1:
weapon_name, weapon_number = find_main_charecters(line.strip())
weapon_dict[weapon_name] = weapon_number
i = i+1
name_sorted = sorted(name_dict.items(), key=lambda item: item[1], reverse=True)
print(name_sorted[0:10])
weapon_sorted = sorted(weapon_dict.items(), key=lambda item: item[1], reverse=True)
print(weapon_sorted[0:10])
函数可变长参数例子
# #取得参数的个数
def howlong(first, *other):
print( 1 + len(other))
howlong(55,66,77)
函数迭代器、生成器
# iter() next()
list1 =[1, 2, 3]
it = iter(list1)
print( next(it))
print( next(it))
print( next(it))
print( next(it)) # except:StopIteration
#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 true():return True
lambda : True
def add(x,y): return x+y
add2 = lambda x,y : x+y
print(add2(5,6))
def testfunc(a_num): def testfunc(a_num):return a_num +1
var = lambda b_num : b_num + 1
print(var(5))
网友评论