Live2D

python的列表生成式

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

通常我们在循环遍历一个列表时,都是通过for循环来完成

L = []
for i in range(1,11)
    L.append(x*x)

结果如下:

[1,4,9,16,25,36,49,64,81,100]

然而,python号称是人生苦短,我用python,那么简单的方法会是什么呢?答案当然是有的

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

通过运行我们发现,可以得到以上的同样结果,这就是python的强大之处,可以简化代码,减少程序员的工作量

我们在写出成列表生成式时,需要把要生成的元素或者表达式写在前面,然后后面跟上for循环,就可以把list创建出来。

for循环后面还可以加上if判断语句:

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

if--else的用法
这里需要注意的是:

不能在for后面的if语句后加上else
else 要在for循环之前,否则会报错

例子:
[错误样式]

[x for x in range(1, 11) if x % 2 == 0 else 0]
  File "<stdin>", line 1
    [x for x in range(1, 11) if x % 2 == 0 else 0]
                                              ^
SyntaxError: invalid syntax

将 if 单独写在 for 前面也会报错

[x if x % 2 == 0 for x in range(1, 11)]
  File "<stdin>", line 1
    [x if x % 2 == 0 for x in range(1, 11)]
                       ^
SyntaxError: invalid syntax

[正确样式]

[x if x % 2 == 0 else -x for x in range(1, 11)]
[-1, 2, -3, 4, -5, 6, -7, 8, -9, 10]

这样子就可以正常输出了
原因:

  • for前面的部分是一个表达式,它必须根据x计算出一个结果。因此,考察表达式:x if x % 2 == 0,它无法根据x计算出结果,因为缺少else,必须加上else
  • 跟在for后面的if是一个筛选条件,不能带else,否则如何筛选?
  • 可见,在一个列表生成式中,for前面的if ... else是表达式,而for后面的if是过滤条件,不能带else。

循环还可以用好几层,以下演示的是两层的

[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可以列出文件和目录
['chardetect.exe', 'easy_install-3.7.exe', 'easy_install.exe', 'pip.exe', 'pip3.7.exe', 'pip3.exe', 'pyppeteer-install-script.py', 'pyppeteer-install.exe', 'tqdm.exe']
>>> [d for d in o
[d for d in os.listdir('..')] # .表示当前目录 ..表示上一级目录
['Animated.py', 'crawler.py', 'DLLs', 'Doc', 'friends.py', 'img', 'include', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'pip', 'pip-19.1.1-py2.py3-none-any.whl', 'pip-19.1.1.tar.gz', 'python.exe', 'python3.dll', 'python37.dll', 'pythonw.exe', 'qweqwewqe.py', 'robots', 'Scripts', 'tcl', 'test.txt', 'Tools', 'vcruntime140.dll', '__pycache__']
posted @ 2020-07-15 22:59  空空道人┞  阅读(319)  评论(0编辑  收藏  举报
复制代码
Live2D