列表生成器為創建列表提供了一種簡潔的方式。
比如說,我們可以這樣實現一個平方數列表
squares=[x**2 for x in range(10)]
或者這樣迭代一個字符串來生成列表
>>> s = 'hello world'
>>> comp = [x for x in s if x != ' ']
>>> print(comp)
['h','e','l','l','o','w','o','r','l','d']
實際上,列表生成式這個概念在Python中被泛化了。不但可以生成列表,還可以生成字典 dict 和集合 set。
>>> s = 'hello world'
>>> comp = {x for x in s}
>>> print(comp)
{' ','h','d','o','l','e','w','r'}
>>> print(type(comp))
<class 'set'>
嚴格來說,字典生成式是這樣的語言:
{key:value for (key,value) in iterable}
而有一個 zip()
函數可以把可迭代的對象作為參數,將對象中對應的元素打包成一個個元組,然后返回由這些元組組成的列表。
>>> s = 'hello world'
>>> dict_comp = {k:v for (k,v) in zip(range(11),s)}
>>> print(dict_comp)
{0:'h',1:'e',2:'l',3:'l',4:'o',5:' ',6:'w',7:'o',8:'r',9:'l',10:'d'}
>>> print(type(dict_comp))
<class 'dict'>
但是,其實對於上面這個簡單的例子,可以不用字典生成式,直接用 dict()
進行轉換也是可以的。
>>> s,i = 'hello world', len(s)
>>> dict_comp = dict(zip(range(i),s))
>>> print(dict_comp)
{0:'h',1:'e',2:'l',3:'l',4:'o',5:' ',6:'w',7:'o',8:'r',9:'l',10:'d'}
>>> print(type(dict_comp))
<class 'dict'>