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

来源:互联网 发布:讲诚信 知礼仪 编辑:程序博客网 时间:2024/05/23 18:14

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

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

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

但是如果要生成[1*1, 2*2 ,3*3, …, 10*10]怎么做?
方法一是循环:

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

但是循环太繁琐,而列表生成器则可以用一行语句代替循环生成上面的list:

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

写列表生成式时,把要生成元素x * x放在前面,后面跟for循环,就可以把list创建出来,十分有用,多谢几次,很快就可以熟悉这种写法。

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 = Cy = Bx = A

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

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

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

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

这里写图片描述
这里写图片描述

小练习:

如果list中既包含字符串,又包含整数,由于非字符串类型没有lower()方法,所以列表生成式就会报错:

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

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

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

请修改列表生成式,通过添加if语句保证列表生成式能正确地执行:

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

这里写图片描述

1 0
原创粉丝点击