• 如果您觉得本站非常有看点，那么赶紧使用Ctrl+D 收藏吧

# Python开发的入门教程(九)-列表生成式

3周前 (09-01) 25次浏览

## 生成列表

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

## 复杂表达式 (TODO)

``````d = { 'Adam': 95, 'Lisa': 85, 'Bart': 59 }
``````

``````tds = ['<tr><td>%s</td><td>%s</td></tr>' % (name, score) for name, score in d.iteritems()]
print '<table>'
print '<tr><th>Name</th><th>Score</th><tr>'
print 'n'.join(tds)
print '</table>'
``````

``````<table border="1">
<tr><th>Name</th><th>Score</th><tr>
<tr><td>Lisa</td><td>85</td></tr>
<tr><td>Bart</td><td>59</td></tr>
</table>
``````

## 条件过滤

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

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

## 多层表达式

for循环可以嵌套，因此，在列表生成式中，也可以用多层 for 循环来生成列表。

``````>>> [m + n for m in 'ABC' for n in '123']
['A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3']
``````

``````L = []
for m in 'ABC':
for n in '123':
L.append(m + n)
``````