列表生成式是Python中非常强大的可以用来创建list的生成式。
如果要生成list[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],可以使用切片:
>>> range(1,11)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
如果是[1*1,2*2,...,10*10]呢,可以使用循环:
>>> L = []
>>> for i in range(1,11):
... L.append(i*i)
...
>>> 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]
后面添加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
>>> [d for d in os.listdir('.')]
['.DS_Store', '20101.py', '20903.py', 'Calculator.py', 'hello.py', 'learning.py', 'mymodule.py', 'tryExcept.py', 'tryExcept1.py']
for循环其实可以同时使用两个甚至多个变量,比如dict的iteritems()可以同时迭代key和value:
>>> d = {'x': 'A', 'y': 'B', 'z': 'C' }
>>> for j,k in d.iteritems():
... print j,'=',k
...
y = B
x = A
z = C
如果是使用列表生成式,那就简约多了:
>>> d = {'x': 'A', 'y': 'B', 'z': 'C' }
>>> [j+'='+k for j,k in d.iteritems()]
['y=B', 'x=A', 'z=C']
把一个list中的字符变成小写:
>>> L = ["Python","Java","Oc","Swift"]
>>> [s.lower() for s in L]
['python', 'java', 'oc', 'swift']
由于非字符串没有lower()的方法,如果list中含有非字符串,则调用lower()会报错:
>>> L = ["Python","Java",100,"Swift"]
>>> [s.lower() for s in L]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute 'lower'
因此,加上判断:
>>> L = ["Python","Java",100,"Swift"]
>>> [s.lower() for s in L if isinstance(s,str)]
['python', 'java', 'swift']
>>>
网友评论