Python迭代、函数定义与参数
目录
1 迭代
1.1 迭代协议 next()
能够获取到下一个元素,用于移动指针关联到下一个元素上
>>> f = open('hello.txt',encoding = 'utf8')
>>> f.__next__()
'baidu www.baidu.com\n'
>>> next(f)
'google www.google.com\n'
>>> f.__next__()
'taobao www.taobao.com'
>>> next(f)
Traceback (most recent call last): #迭代结束了
File "<stdin>", line 1, in <module>
StopIteration
1.2 迭代工具 for…推导…map…
for…推导…map…之所以能够遍历对象,是因为程序在目标上应用了迭代器
1.迭代器对象
已经原先就应用了迭代器
2.可迭代对象
iter() - > iter() 用于生成迭代器
注意:因为 list本身内部比较复杂,Python并没有预先为list实现好迭代器,因此需要手动创建迭代器。
>>> f = open('hello.txt',encoding = 'utf8')
>>> iter(f) is f #f是否是迭代器对象
True #文件类型已经应用了迭代器,是迭代器对象
>>> url = [1,2,3]
>>> iter(url) is url
False #列表类型没有原先就应用了迭代器,但他是可迭代对象
>>> l = iter(url) #列表是可迭代对象,可应用一个迭代器
>>> l.__next__()
1
>>> l.__next__()
2
1.3 内置可迭代对象
内置可迭代对象有:range(),map(),zip()…
例子:
map()方法
def double_number(x):
return x**2
l = [1,2,3,4,5]
result = list(map(double_number,l)) #对l中每个元素应用double_number()方法
print(result)
[1, 4, 9, 16, 25]
zip()
l1 = [1,2,3,4,5]
l2 = [6,7,8,9,0]
result = list(zip(l1,l2)) #把两个列表的元素按位置一一对应组成元组
print(result)
[(1, 6), (2, 7), (3, 8), (4, 9), (5, 0)]
2 函数
2.1 函数的作用
最大化代码重用
最小化代码冗余
过程分解
2.2 函数的定义
def 方法名 (参数1,参数2...)
2.3 函数的调用
函数名(实际参数)
2.4 变量的作用域
Build-in 内置变量
Global和Local变量
x = 55 #在函数外部定义全局变量x
def func():
global y = 3 #在函数内部定义全局变量y
x = 99 #局部变量
return x
print("全局x = ",x)
print("func函数内x = ",func())
print("全局y = ",y)
全局x = 55
func函数内x = 99
全局y = 33
Enclousure封装
def func():
x = 99 #enclousore封装
def nested():
x = 100
print(x)
nested()
return x
nonlocal 声明非局部变量
def func():
x = 99
def nested():
nonlocal x
x = 100
print(x)
nested()
print(x)
func()
100
100
2.5 参数
1.参数传递
通俗来讲,传递的意思就是把数据传递到函数内部,让其对数据进行操作
不可变类型,传递副本给函数,函数内对象不影响原始值,例如int型、字符串str
可变类型,传递地址引用,函数内操作可能会影响原始值,例如列表list
def change_number(x):
x+=1
def change_list(list):
list[0] = 'change'
def change_str(str):
str = 'change'
x =1
list = [6,6,6]
str = '666'
change_number(x)
change_list(list)
change_str(str)
print(x)
print(list)
print(str)
1
['change', 6, 6]
666
2.参数匹配
位置匹配
关键字匹配
def func(a,b,c):
print(a,b,c)
func(1,2,3) #位置匹配
func(c = 1,b = 2,a = 3) #关键字匹配
1 2 3
3 2 1
默认值(调用时省略传值)
def func(a,b = 1,c = 3):
print(a,b,c)
func(a = 1) #b和c都默认匹配
func(1,2,c = 1) #传入其他值时不按默认
1 1 3
1 2 1
*args 任意数量参数
def avg(*scores): #可以传入任意数量的参数
return sum(scores) / len(scores)
result = avg(1,2,3,4,5)
print(result)
2.5
如果要传入元组tulple内的多个数据,应该用 * 进行解包
def avg(*scores): #可以传入任意数量的参数
return sum(scores) / len(scores)
scores = (1,2,3,4)
result = avg(*scores)
print(result)
2.5
e.**kwargs
d = {'name':'Tom','age':23,'job':'worker'}
d2 = dict(name='Tom',age=23,job='worker')
def display(**person):
print(person)
display(name='Tom',age=23,job='worker') #可以通过传入键值对的方式
display(**d) #可以通过解包字典的方式
{'name': 'Tom', 'age': 23, 'job': 'worker'}
{'name': 'Tom', 'age': 23, 'job': 'worker'}
需要注意的是不论是dict方法还是自定义方法,传入键值对的时候键值对中的键不能加引号