版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
迭代
# 最简单的
# 使用for为对象生成可迭代对象 __next__(), 迭代器对象
nums = [1,2,3,4]
for n in nums:
print(n) # 输出 1 2 3 4
# 使用__next__()迭代
iter(nums) .__next__()
# 可迭代方法
# map
nums_str = list(map(str, nums)) #['1','2','3','4']
# zip
# [('a','1'), ('b', '2'),('c', '3'),('d','4')]
nums_zip = list(zip(['a','b','c','d'], nums))
# filter
def is_odd(n):
return n % 2 == 1
# 保留 True(1) 因为if 1 返回True
nums_odd = list(filter(is_odd, nums))
函数与参数
python 函数使用 def 开始函数定义,接着是函数名,括号内部为函数的参数。
函数的返回:以return 返回值并终止函数,yield 只返回值并不终止函数。
def my_iter():
for i in range(10):
return 1
def my_yield():
for i in range(10):
yield i
my_iter() # 就是个int
for item in my_iter(): # 报错 'int' object is not iterable
print(item)
for item in my_yield():
print(item) # 输出0,1,2,3,4,5,6,7,8,9
函数中的参数:可变类型和不可变类型
# 不可变类型 string
input_str = 'hello'
def myadd(n):
n += 'end'
return
#
myadd(input_str )
print(input_str ) # hello
input_list = ['hello']
def myadd2(n):
n.append('end')
return
myadd2(input_list)
print(input_list) # ['hello', 'end]
# 若不想改变传入的参数,传入副本
myadd2(input_list[:])
myadd2(input_list.copy())
参数的作用域(由大到小):
- built-in
- global
- Enclousure (nolocal)
- local
x = 5
def func():
x = 99
print(x)
func() # 输出99 x还是为5
# global # 可以使用在任意位置
x = 5
def func1():
global x
x = 99
print(x)
func1() # x 变为 99
# nolocal 只能使用在嵌套函数中
def func2():
x = 5
def core():
nolocal x
x = 99
core()
print(x) # 99
func()