# 在python中使用列表生成式的教程

>>> 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可以列出文件和目录
[‘.emacs.d’, ‘.ssh’, ‘.trash’, ‘adlm’, ‘applications’, ‘desktop’, ‘documents’, ‘downloads’, ‘library’, ‘movies’, ‘music’, ‘pictures’, ‘public’, ‘virtualbox vms’, ‘workspace’, ‘xcode’]

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

>>> d = {‘x’: ‘a’, ‘y’: ‘b’, ‘z’: ‘c’ }
>>> for k, v in d.iteritems():
… print k, ‘=’, v

y = b
x = a
z = c

>>> d = {‘x’: ‘a’, ‘y’: ‘b’, ‘z’: ‘c’ }
>>> [k + ‘=’ + v for k, v in d.iteritems()]
[‘y=b’, ‘x=a’, ‘z=c’]

>>> 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 “”, line 1, in
attributeerror: ‘int’ object has no attribute ‘lower’

>>> x = ‘abc’
>>> y = 123
>>> isinstance(x, str)
true
>>> isinstance(y, str)
false

Posted in 未分类