[关闭]
@yanglt7 2018-11-14T03:26:15.000000Z 字数 2569 阅读 611

Python10_列表生成式和生成器

Python


列表生成式

列表生成式即List Comprehensions,是Python内置的非常简单却强大的可以用来创建list的生成式。

要生成list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]可以用list(range(1, 11)):

  1. >>> list(range(1, 11))
  2. [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

要生成[1x1, 2x2, 3x3, ..., 10x10]。

方法一是循环:

  1. >>> L = []
  2. >>> for x in range(1, 11):
  3. ... L.append(x * x)
  4. ...
  5. >>> L
  6. [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

列表生成式则可以用一行语句代替循环生成上面的list:

  1. >>> [x * x for x in range(1, 11)]
  2. [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

写列表生成式时,把要生成的元素x * x放到前面,后面跟for循环:

for循环后面还可以加上if判断,这样我们就可以筛选出仅偶数的平方:

  1. >>> [x * x for x in range(1, 11) if x % 2 == 0]
  2. [4, 16, 36, 64, 100]

还可以使用两层循环,可以生成全排列:

  1. >>> [m + n for m in 'ABC' for n in 'XYZ']
  2. ['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']

列出当前目录下的所有文件和目录名,可以通过一行代码实现:

  1. >>> import os # 导入os模块,模块的概念后面讲到
  2. >>> [d for d in os.listdir('.')] # os.listdir可以列出文件和目录

for循环其实可以同时使用两个甚至多个变量,比如dict的items()可以同时迭代key和value:

  1. >>> d = {'x': 'A', 'y': 'B', 'z': 'C' }
  2. >>> for k, v in d.items():
  3. ... print(k, '=', v)
  4. ...
  5. y = B
  6. x = A
  7. z = C

因此,列表生成式也可以使用两个变量来生成list:

  1. >>> d = {'x': 'A', 'y': 'B', 'z': 'C' }
  2. >>> [k + '=' + v for k, v in d.items()]
  3. ['y=B', 'x=A', 'z=C']

最后把一个list中所有的字符串变成小写:

  1. >>> L = ['Hello', 'World', 'IBM', 'Apple']
  2. >>> [s.lower() for s in L]
  3. ['hello', 'world', 'ibm', 'apple']

使用内建的isinstance函数可以判断一个变量是不是字符串:

  1. >>> x = 'abc'
  2. >>> y = 123
  3. >>> isinstance(x, str)
  4. True
  5. >>> isinstance(y, str)
  6. False

生成器

在Python中,一边循环一边计算的机制,称为生成器:generator。

要创建一个generator,有很多种方法。

第一种方法很简单,只要把一个列表生成式的[]改成(),就创建了一个generator:

  1. >>> L = [x * x for x in range(10)]
  2. >>> L
  3. [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
  4. >>> g = (x * x for x in range(10))
  5. >>> g
  6. <generator object <genexpr> at 0x1022ef630>

如果要一个一个打印出来,可以通过next()函数获得generator的下一个返回值:

  1. >>> next(g)
  2. 0
  3. >>> next(g)
  4. 1
  5. ...
  6. ...
  7. >>> next(g)
  8. 64
  9. >>> next(g)
  10. 81
  11. >>> next(g)
  12. Traceback (most recent call last):
  13. File "<stdin>", line 1, in <module>
  14. StopIteration

正确的方法是使用for循环,因为generator也是可迭代对象:

  1. >>> g = (x * x for x in range(10))
  2. >>> for n in g:
  3. ... print(n)
  4. ...
  5. 0
  6. 1
  7. 4
  8. 9
  9. 16
  10. 25
  11. 36
  12. 49
  13. 64
  14. 81

所以,我们创建了一个generator后,基本上永远不会调用next(),而是通过for循环来迭代它,并且不需要关心StopIteration的错误。

generator非常强大。如果推算的算法比较复杂,用类似列表生成式的for循环无法实现的时候,还可以用函数来实现。

比如,著名的斐波拉契数列(Fibonacci),除第一个和第二个数外,任意一个数都可由前两个数相加得到:

1, 1, 2, 3, 5, 8, 13, 21, 34, ...

斐波拉契数列用列表生成式写不出来,但是,用函数把它打印出来却很容易:

  1. def fib(max):
  2. n, a, b = 0, 0, 1
  3. while n < max:
  4. print(b)
  5. a, b = b, a + b
  6. n = n + 1
  7. return 'done'
  8. >>> fib(6)

要把fib函数变成generator,只需要把print(b)改为yield b就可以了:

  1. def fib(max):
  2. n, a, b = 0, 0, 1
  3. while n < max:
  4. yield (b)
  5. a, b = b, a + b
  6. n = n + 1
  7. return 'done'

这就是定义generator的另一种方法。如果一个函数定义中包含yield关键字,那么这个函数就不再是一个普通函数,而是一个generator:在每次调用next()的时候执行,遇到yield语句返回,再次执行时从上次返回的yield语句处继续执行。

把函数改成generator后,直接使用for循环来迭代:

  1. >>> for n in fib(6):
  2. ... print(n)
  3. ...
  4. 1
  5. 1
  6. 2
  7. 3
  8. 5
  9. 8

但是用for循环调用generator时,发现拿不到generator的return语句的返回值。如果想要拿到返回值,必须捕获StopIteration错误,返回值包含在StopIteration的value中:

  1. >>> g = fib(6)
  2. >>> while True:
  3. ... try:
  4. ... x = next(g)
  5. ... print('g:', x)
  6. ... except StopIteration as e:
  7. ... print('Generator return value:', e.value)
  8. ... break
  9. ...
  10. g: 1
  11. g: 1
  12. g: 2
  13. g: 3
  14. g: 5
  15. g: 8
  16. Generator return value: done
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注