文章目录
- 迭代
- 练习
- 列表生成式
- 列表生成式中的 if ... else ...
- 练习
- 生成器
- 练习
- 迭代器
迭代
如果给定一个list
或tuple
或者其他可迭代对象,python可以通过for
循环来遍历这个对象,这种遍历称为迭代(Iteration)。
判断一个对象是否是可迭代对象,方法是通过collections.abc
模块的Iterable
类型进行判断:
from collections.abc import Iterable
print(isinstance('abc', Iterable)) # True 字符串
print(isinstance([1, 2, 3], Iterable)) # True 列表
print(isinstance(123, Iterable)) # False 整数不能进行迭代
print(isinstance({}, Iterable)) # True 字典
字典的迭代:
# dict 迭代 key
d = {'a': 1, 'b': 2, 'c': 3}
for key in d:
print(key)
# dict 迭代 key 与 value
for key, value in d.items():
print(f"key:{key}, value:{value}")
结果如下:
a
b
c
key:a, value:1
key:b, value:2
key:c, value:3
Python内置的enumerate
函数可以把一个list
变成索引-元素对,可以在for
循环中同时迭代索引和元素本身:
L = ['a', 'b', 'c']
for i, value in enumerate(L, 0): # 0 代表从0开始索引,可省略
print(i, value)
0 a
1 b
2 c
for
循环中,同时引用两个变量,在Python里也很常见:
for name, score in [('Mark', 100), ('Lucy', 98), ('Tom', 76)]:
print(name, "\t", score)
for x, y in [(1, 4), (2, 8), (3, 12)]:
print(x, y)
结果如下:
Mark 100
Lucy 98
Tom 76
1 4
2 8
3 12
练习
题目:请使用迭代查找一个list中最小和最大值,并返回一个tuple。
def findMinAndMax(L):
if len(L) == 0:
return (None, None)
i_min = min(L)
i_max = max(L)
return (i_min, i_max)
L1 = []
L2 = [7]
L3 = [7, 1]
L4 = [7, 1, 3, 5, 9]
print(findMinAndMax(L1))
print(findMinAndMax(L2))
print(findMinAndMax(L3))
print(findMinAndMax(L4))
结果如下:
(None, None)
(7, 7)
(1, 7)
(1, 9)
列表生成式
列表生成式即 List Comprehensions,是Python内置的非常简单却强大的可以用来创建list的生成式。
>>> list(range(1, 11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
用 for 循环创建列表生成式:
>>> [x * x for x in range(1, 11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
在 for 循环后面可以加上 if 判断,这里筛选出仅偶数的平方:
>>> [x * x for x in range(1, 11) if x % 2 == 0]
[4, 16, 36, 64, 100]
使用两层循环,可以生成全排列;但三层和三层以上的循环就很少用到了:
>>> [m+n for m in 'ABC' for n in 'XYZ']
['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']
列出某一目录下的所有文件和目录名:
>>> import os
>>> [d for d in os.listdir('E:/submit/')]
['.idea', 'GUI', 'submit', '__MACOSX']
列表生成式可以使用两个变量生成 list :
>>> d = {'a': 'A', 'b': 'B', 'c': 'C'}
>>> [k+'='+v for k, v in d.items()]
['a=A', 'b=B', 'c=C']
将一个 list 中所有的字符串变成小写:
>>> L = ['Hello', 'World', 'IBM', 'Apple']
>>> [s.lower() for s in L]
['hello', 'world', 'ibm', 'apple']
列表生成式中的 if … else …
正确写法:
# 1.生成偶数
>>> [x for x in range(11) if x % 2 == 0]
[0, 2, 4, 6, 8, 10]
# 2.奇数取相反数,偶数不变
>>> [x if x % 2 == 0 else -x for x in range(11)]
[0, -1, 2, -3, 4, -5, 6, -7, 8, -9, 10]
对于正确写法的 if…else… 的列表生成式的理解:
L = []
for x in range(11): # 第1层
if x % 2 == 0: # 第2层
L.append(x)
else:
L.append(-x)
print(L)
错误写法:
>>> [x for x in range(11) if x % 2 ==0 else 0]
SyntaxError: invalid syntax
>>> [x if x % 2 == 0 for x in range(11)]
SyntaxError: invalid syntax
练习
输入:L1 = [‘Hello’, ‘World’, 18, ‘Apple’, None]
输出:L2 == [‘hello’, ‘world’, ‘apple’]
>>> L1 = ['Hello', 'World', 18, 'Apple', None]
>>> [x.lower() for x in L1 if isinstance(x, str)]
['hello', 'world', 'apple']
生成器
通过列表生成式,我们可以直接创建一个列表。但是,受到内存限制,列表容量肯定是有限的。而且,创建一个包含100万个元素的列表,不仅占用很大的存储空间,如果我们仅仅需要访问前面几个元素,那后面绝大多数元素占用的空间都白白浪费了。
在循环的过程中不断推算出后续的元素,不必创建完整的 list,从而节省大量的空间。在Python中,这种一边循环一边计算的机制,称为生成器(generator),保存的是算法。
要创建一个 generator,有很多种方法。
第一种方法:只要把一个列表生成式的[]
改成()
,就创建了一个 generator。
L
是一个 list ,g
是一个 generator 。
可以通过next()
函数获得 generator 的下一个返回值,将元素打印出来。直到计算到最后一个元素,没有更多的元素时,会抛出StopIteration
的错误。
>>> L = [x * x for x in range(10)]
>>> L
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> g = (x * x for x in range(10))
>>> g
<generator object <genexpr> at 0x00000239099345F0>
>>> next(g)
0
>>> next(g)
1
>>> next(g)
4
>>> # 此处省略
>>> next(g)
81
>>> next(g)
Traceback (most recent call last):
File "<pyshell#33>", line 1, in <module>
next(g)
StopIteration
因为 generator 也是可迭代对象,正确方法是使用for
循环来调用:
>>> for i in g:
print(i)
0
1
4
9
16
25
36
49
64
81
定义 generator 的第二种方法:如果一个函数定义中包含yield
关键字,那么这个函数就不再是一个普通函数,而是一个 generator 函数,调用一个 generator 函数将返回一个 generator:
# 斐波那契数列
def fib(max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a + b
n = n + 1
return 'done'
f = fib(max)
print(f) # 结果:<generator object fib at 0x000001CA9FAD1048>
for i in f:
print(i, end="\t")
# 结果:1 1 2 3 5 8
- 普通函数是顺序执行,遇到
return
语句或者最后一行函数语句就返回。 - generator 函数,在每次调用
next()
的时候执行,遇到yield
语句返回,再次执行时从上次返回的yield
语句处继续执行。
用for
循环调用 generator 时,发现拿不到 generator 的return
语句的返回值'done'
。如果想要拿到返回值,必须捕获StopIteration
错误,返回值包含在StopIteration
的value
中:
g = fib(6)
while True:
try:
x = next(g)
print('g:', x)
except StopIteration as e:
print('Generator return value:', e.value)
break
结果如下:
g: 1
g: 1
g: 2
g: 3
g: 5
g: 8
Generator return value: done
定义一个简单的 generator 函数,依次返回数字1,3,5:
def odd():
print('step1:')
yield 1
print('step2:')
yield 3
print('step:')
yield 3
调用该 generator 函数时,首先要生成一个generator对象,然后用next()
函数不断获得下一个返回值:
o = odd() # 创建一个对象
print(next(o))
print(next(o))
print(next(o))
print(next(o))
执行3次yield
后,已经没有yield
可以执行了,所以,第4次调用next(o)
就报错。结果如下:
step1:
1
step2:
3
step:
3
Traceback (most recent call last):
File "E:/csdn/3_高级特性_迭代.py", line 139, in <module>
print(next(o))
StopIteration
如果没有创建一个 generator 对象,然后不断对这一个 generator 对象调用next()
;而是直接使用odd()
,那么每次都会创建一个新的 generator 对象,下面的代码实际上创建了3个完全独立的generator,对3个generator分别调用next()
,那么每个都会返回第一个值1。
>>> next(odd())
step 1
1
>>> next(odd())
step 1
1
>>> next(odd())
step 1
1
练习
1
/ \
1 1
/ \ / \
1 2 1
/ \ / \ / \
1 3 3 1
/ \ / \ / \ / \
1 4 6 4 1
/ \ / \ / \ / \ / \
1 5 10 10 5 1
杨辉三角,把每一行看做一个list,试写一个generator,不断输出下一行的list:
def triangles():
L = [1]
while True:
yield L
L = [L[x] + L[x+1] for x in range(len(L) - 1)] # 计算下一行中间的值
L.insert(0, 1) # 在开头插入1
L.append(1) # 在结尾添加1
# 前面3行可以替换成下面这句
# L = [1] + [L[x] + L[x+1] for x in range(len(L) - 1)] + [1]
if len(L) > 10: # 仅输出10行
break
输出结果如下:
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
[1, 6, 15, 20, 15, 6, 1]
[1, 7, 21, 35, 35, 21, 7, 1]
[1, 8, 28, 56, 70, 56, 28, 8, 1]
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
迭代器
可迭代对象Iterable
:直接作用于for
循环的对象。可以使用isinstance()
判断一个对象是否是Iterable
对象:
from collections.abc import Iterable
print(isinstance('abc', Iterable)) # True 字符串
print(isinstance([1, 2, 3], Iterable)) # True 列表
print(isinstance(123, Iterable)) # False 整数不能进行迭代
print(isinstance({}, Iterable)) # True 字典
print(isinstance((x for x in range(10)), Iterable)) # True generator生成器
迭代器Iterator
:可以被next()
函数调用并不断返回下一个值的对象。可以使用isinstance()
判断一个对象是否是Iterator
对象:
from collections.abc import Iterator
print(isinstance((x for x in range(10)), Iterator)) # True generator生成器
print(isinstance([], Iterator)) # False
print(isinstance({}, Iterator)) # False
print(isinstance('abc', Iterator)) # False
可以看出,生成器既是可迭代对象Iterable
,也是迭代器是Iterator
。但list
、dict
、str
虽然是Iterable
,却不是Iterator
。
为什么list
、dict
、str
等数据类型不是Iterator
?
这是因为Python的Iterator
对象表示的是一个数据流,Iterator
对象可以被next()
函数调用并不断返回下一个数据,直到没有数据时抛出StopIteration
错误。可以把这个数据流看做是一个有序序列,但我们却不能提前知道序列的长度,只能不断通过next()
函数实现按需计算下一个数据,所以Iterator
的计算是惰性的,只有在需要返回下一个数据时它才会计算。
Iterator
甚至可以表示一个无限大的数据流,例如全体自然数。而使用list是永远不可能存储全体自然数的。
使用iter()
函数可以把list
、dict
、str
等Iterable
变成Iterator
:
print(isinstance(iter([]), Iterator)) # True
print(isinstance(iter('abc'), Iterator)) # True
print(isinstance(iter({}), Iterator)) # True
Python的for
循环本质上就是通过不断调用next()
函数实现的,例如:
for x in [1, 2, 3, 4, 5]:
pass
实际上完全等价于:
# 首先获得Iterator对象:
it = iter([1, 2, 3, 4, 5])
# 循环:
while True:
try:
# 获得下一个值:
x = next(it)
except StopIteration:
# 遇到StopIteration就退出循环
break