标签:范围 情况 比较 数据类型 其他 关键字 div 列表 ems
>>> d = {‘a‘: 1, ‘b‘: 2, ‘c‘: 3} >>> for key in d: ... print(key) ... a c b
for value in d.values() # 迭代value
for k, v in d.items() # 同时迭代key和value
>>> from collections import Iterable >>> isinstance(‘abc‘, Iterable) # str是否可迭代 True >>> isinstance([1,2,3], Iterable) # list是否可迭代 True >>> isinstance(123, Iterable) # 整数是否可迭代 False
>>> L = [] >>> for x in range(1, 11): ... L.append(x * x) ... >>> L [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>> [x * x for x in range(1, 11)] [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>> [m + n for m in ‘ABC‘ for n in ‘XYZ‘] [‘AX‘, ‘AY‘, ‘AZ‘, ‘BX‘, ‘BY‘, ‘BZ‘, ‘CX‘, ‘CY‘, ‘CZ‘]
>>> L = [‘Hello‘, ‘World‘, ‘IBM‘, ‘Apple‘] >>> [s.lower() for s in L] [‘hello‘, ‘world‘, ‘ibm‘, ‘apple‘]
>>> d = {‘x‘: ‘A‘, ‘y‘: ‘B‘, ‘z‘: ‘C‘ } >>> [k + ‘=‘ + v for k, v in d.items()] [‘y=B‘, ‘x=A‘, ‘z=C‘]
lower()
方法,所以列表生成式会报错,L1 = [‘Hello‘, ‘World‘, 18, ‘Apple‘, None] L2 = [s.lower() for s in L1 if isinstance(s, str)] print(L2) # 输出: [‘hello‘, ‘world‘, ‘apple‘]
[]
改成()
,就创建了一个generator:>>> 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 0x1022ef630>
L
和g
的区别仅在于最外层的[]
和()
,L
是一个list,而g
是一个generator。next()
函数获得generator的下一个返回值next(g)
,就计算出g
的下一个元素的值,直到计算到最后一个元素,没有更多的元素时,抛出StopIteration
的错误。但是不断调用next(g)
实在是太变态了,正确的方法是使用for
循环,因为generator也是可迭代对象. 所以,我们创建了一个generator后,基本上永远不会调用next()
,而是通过for
循环来迭代它,并且不需要关心StopIteration
的错误。for
循环无法实现的时候,还可以用函数来实现。def fib(max): n, a, b = 0, 0, 1 while n < max: print(b) a, b = b, a + b n = n + 1 return ‘done‘
fib
函数实际上是定义了斐波拉契数列的推算规则,可以从第一个元素开始,推算出后续任意的元素,这种逻辑其实非常类似generator。fib
函数变成generator,只需要把print(b)
改为yield b
就可以了: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
关键字,那么这个函数就不再是一个普通函数,而是一个generator1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1
def triangles(): L = [1] while True: yield L L.append(0) L = [L[i - 1] + L[i] for i in range(len(L))] n = 0 for t in triangles(): print(t) n = n + 1 if n == 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]
for
循环的数据类型有以下几种:>>> from collections import Iterable >>> isinstance([], Iterable) True >>> isinstance({}, Iterable) True >>> isinstance(‘abc‘, Iterable) True >>> isinstance((x for x in range(10)), Iterable) True >>> isinstance(100, Iterable) False
>>> from collections import Iterator >>> isinstance((x for x in range(10)), Iterator) True >>> isinstance([], Iterator) False >>> isinstance({}, Iterator) False >>> isinstance(‘abc‘, Iterator) False
>>> isinstance(iter([]), Iterator) True >>> isinstance(iter(‘abc‘), Iterator) True
标签:范围 情况 比较 数据类型 其他 关键字 div 列表 ems
原文地址:http://www.cnblogs.com/cotsnail/p/6410406.html