Python 的高级特性：列表推导式、生成器与迭代器 点赞 2

列表推导式

``````In [23]: {i:el for i,el in enumerate(["one","two","three"])}
Out[23]: {0: 'one', 1: 'two', 2: 'three'}``````

enumerate 是内建函数，可以让列表获得「下标」的属性，而如果不用列表推导式，上例需要这么写：

``````In [24]: lst = ["one","two","three"]

In [25]: i = 0

In [26]: for e in lst:
....:     lst[i] = '%d: %s' % (i,lst[i])
....:     i +=1
....:

In [27]: lst
Out [27]: ['0: one', '1: two', '2: three']``````

迭代器

``````In [29]: import sys

In [30]: i = iter(range(10000))

In [32]: id(i.__next__())
Out[32]: 4388723488

In [33]: sys.getsizeof(i)
Out[33]: 48

In [34]: sys.getsizeof(i.__next__())
Out[34]: 28

In [35]: e = range(10000)

In [37]: sys.getsizeof(e)
Out[37]: 48

In [38]: sys.getsizeof(list(e))
Out[38]: 90112``````

生成器「generator」

生成生成器的两种方法

``In [40]: g = (x*x for x in range(10))``

如何判断一个函数是否是生成器

``````In [41]: dir(g)
Out[41]:
['__class__',
...
'__next__',
...
'__repr__',
'__setattr__',
]``````

``````In [42]: g.__next__()
Out[42]: 0

In [43]: g.__next__()
Out[43]: 1

In [44]: next(g)
Out[44]: 4``````

(=￣ω￣=)··· 暂无内容！

请勿发布不友善或者负能量的内容。与人为善，比聪明更重要！

25

196

821

53