迭代字典
d = {'a': 1, 'b': 2, 'c': 3}
"""
默认情况下,dict迭代的是key
a
b
c
"""
for key in d:
print(key)
"""
如果要迭代value,可以用for value in d.values()
1
2
3
"""
for v in d.values():
print(v)
"""
如果要同时迭代key和value,可以用for k, v in d.items()
('a', 1)
('b', 2)
('c', 3)
"""
for i in d.items():
print(i)
如何判断一个对象是可迭代对象呢?
from collections import Iterable
print(isinstance('ABC', Iterable))
print(isinstance([1,2,3], Iterable))
print(isinstance(121, Iterable))
enumerate函数
Python内置的enumerate函数可以把一个list变成索引-元素对,这样就可以在for循环中同时迭代索引和元素本身:
a = enumerate([1, 2, 3])
print(type(a), a, sep='\n')
for i, v in a:
print(i, v, sep='\t')
<class 'enumerate'>
<enumerate object at 0x0000011ED7C7F708>
0 1
1 2
2 3
列表生成式
>>> [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']
# 把一个list中所有的字符串变成小写
>>> L = ['Hello', 'World', 'IBM', 'Apple']
>>> [s.lower() for s in L]
['hello', 'world', 'ibm', 'apple']
list中既包含字符串,又包含整数,把一个list中所有的字符串变成小写
L1 = ['Hello', 'World', 18, 'Apple', None]
L2 = [s.lower() for s in L1 if isinstance(s, str)]
print(L2)
if L2 == ['hello', 'world', 'apple']:
print('测试通过!')
else:
print('测试失败!')
生成器generator
只要把一个列表生成式的[]改成(),就创建了一个generator
>>> g = (x for x in range(10))
>>> g
<generator object <genexpr> at 0x1022ef630>
通过next()函数获得generator的下一个返回值
>>> next(g)
0
>>> next(g)
1
>>> next(g)
4
>>> next(g)
9
>>> next(g)
16
>>> next(g)
25
>>> next(g)
36
>>> next(g)
49
>>> next(g)
64
>>> next(g)
81
>>> next(g)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
使用for循环
>>> g = (x * x for x in range(10))
>>> for n in g:
... print(n)
...
0
1
4
9
16
25
36
49
64
81
把函数变成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'
如果一个函数定义中包含yield关键字,那么这个函数就不再是一个普通函数,而是一个generator。generator和函数的执行流程不一样。函数是顺序执行,遇到return语句或者最后一行函数语句就返回。而变成generator的函数,在每次调用next()的时候执行,遇到yield语句返回,再次执行时从上次返回的yield语句处继续执行.
>>> for n in fib(6):
... print(n)
...
1
1
2
3
5
8
练习
杨辉三角定义如下:
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[i]+L[i+1] for i in range(len(L)-1)]
L.insert(0, 1)
L.append(1)