# Python教程学习简记5--Python 列表生成式(List Comprehensions)

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

>>> 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]

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

>>> [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']

>>> import os # 导入os模块，后面会讲到模块的概念
>>> [d for d in os.listdir('.')] # os.listdir可以列出文件和目录
['.sudo_as_admin_successful', '.gconf', '下载', '.watershed', 'FeelUOwn', '.macromedia', '.node_repl_history', '视频', '桌面', '.gitconfig', '.vim', '图片', '.xsession-errors.old', '音乐', '.vim_old', '.pki', 'examples.desktop', '.bashrc~', '.bash_history', '.vimrc_old', '.FeelUOwn', '.cache', '.ssh', '.kingsoft', '公共的', '.dbus', '.xinputrc', '.python_history', '.gemrc', '.profile', '.config', '.gvfs', '.oracle_jre_usage', '.dmrc', '.presage', '.pam_environment', 'hjrblog', '.bashrc', '.ICEauthority', '.adobe', '.viminfo', '.xsession-errors', '.apport-ignore.xml', '.Xauthority', '.mozilla', '文档', '.vimrc', '.local', '.gstreamer-0.10', '模板', '.bash_logout', '.nvm', '.npm']

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

>>> d = {'x':'A', 'y':'B', 'z':'C'}
>>> for k, v in d.items():
...     print(k, '=', v)
...
z = C
y = B
x = A

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

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

>>> L = ['Hello', 'World', 18, 'Apple', 'None']
>>> [s.lower() for s in L]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <listcomp>
AttributeError: 'int' object has no attribute 'lower'

>>> x = 'abc'
>>> y = 123
>>> isinstance(x, str)
True
>>> isinstance(y, str)
False

>>> L1 = ['Hello', 'World', 18, 'Apple', 'None']
>>> [s.lower() for s in L1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <listcomp>
AttributeError: 'int' object has no attribute 'lower'

>>> L2 = [s.lower() for s in L1 if isinstance(s, str)]
>>> L2
['hello', 'world', 'apple', 'none']