# 跟老齐学Python之再深点，更懂list

list解析

```
>>> power2 = []
>>> for i in range(1,10):
...   power2.append(i*i)
...
>>> power2
[1, 4, 9, 16, 25, 36, 49, 64, 81]

```

python有一个非常有意思的功能，就是list解析，就是这样的：

```
>>> squares = [x**2 for x in range(1,10)]
>>> squares
[1, 4, 9, 16, 25, 36, 49, 64, 81]

```

```
List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.

```

```
aliquot = []

for n in range(1,100):
if n%3 == 0:
aliquot.append(n)

print aliquot

```

```
>>> aliquot = [n for n in range(1,100) if n%3==0]
>>> aliquot
[3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99]

```

```
>>> mybag = [' glass',' apple','green leaf ']  #有的前面有空格，有的后面有空格
>>> [one.strip() for one in mybag]       #去掉元素前后的空格
['glass', 'apple', 'green leaf']
enumerate

```

```
>>> for i in range(len(week)):
...   print week[i]+' is '+str(i)   #注意，i是int类型，如果和前面的用+连接，必须是str类型
...
monday is 0
sunday is 1
friday is 2

```

python中提供了一个内置函数enumerate，能够实现类似的功能

```
>>> for (i,day) in enumerate(week):
...   print day+' is '+str(i)
...
monday is 0
sunday is 1
friday is 2

```

Return an enumerate object. sequence must be a sequence, an iterator, or some other object which supports iteration. The next() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over sequence:

```
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

```

QQ号联系： 360901061

【本文对您有帮助就好】