Discuss / Python / 列表生成式总结

列表生成式总结

Topic source

老夫007

#1 Created at ... [Delete] [Delete and Lock User]

#我花了三四行,别人的作业一行搞定,学习了,继续加油#

#庆幸我的四行还是完美地解释了整个非常简单的逻辑#

#非常干货简单明了的一节#

L2 = [s.lower() for s in L1 if isinstance(s, str)]

L1 = ['Hello', 'World', 18, 'Apple', None]

L2 = []

for x in L1:

        if isinstance(x, str) == True:

               x = x.lower()

               L2.append(x)

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

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

[x * x for x inrange(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**可以列出文件和目录

['.emacs.d', '.ssh', '.Trash', 'Adlm', 'Applications', 'Desktop', 'Documents', 'Downloads', 'Library', 'Movies', 'Music', 'Pictures', 'Public', 'VirtualBox VMs', 'Workspace', 'XCode']

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

>>> d = {'x': 'A', 'y': 'B', 'z': 'C' }

>>> for k, v ind.items():

... print(k, '=', v)

...

y = B

x = A

z = C

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

>>> d = {'x': 'A', 'y': 'B', 'z': 'C' }

>>> [k + '=' + v for k, v ind.items()]

['y=B', 'x=A', 'z=C']

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

>>> L = ['Hello', 'World', 'IBM', 'Apple']

>>> [s.lower() for s in L]

['hello', 'world', 'ibm', 'apple']

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

>>> x = 'abc'

>>> y = 123

>>> isinstance(x,str)

True

>>> isinstance(y,str)

False


  • 1

Reply