Python 拓展之推导式（列表，字典，集合，生成器推导式）

### 列表推导式

>>> my_list = []
>>> my_list.append(0)
>>> my_list.append(1)
>>> my_list.append(2)
>>> my_list.append(3)
>>> my_list.append(4)
>>> my_list.append(5)
>>> my_list
[0, 1, 2, 3, 4, 5]

>>> my_list = []
>>> for i in range(0,6):
...     my_list.append(i)
...
>>> my_list
[0, 1, 2, 3, 4, 5]

>>> my_list = [i for i in range(0,6)]
>>> my_list
[0, 1, 2, 3, 4, 5]

>>> my_list = [i*i for i in range(0,6)]
>>> my_list

>>> my_list = [i for i in range(0,6) if i  % 2 == 1]
>>> my_list
[1, 3, 5]

>>> first = range(1,4)
>>> second = range(7,9)
>>> for i in first:
...    for j in second:
...            print(i,j)
...
1 7
1 8
2 7
2 8
3 7
3 8

>>> first = range(1,4)
>>> second = range(7,9)
>>> results = [(i,j) for i in first for j in second]
>>> for result in results:
...     print(result)
...
(1, 7)
(1, 8)
(2, 7)
(2, 8)
(3, 7)

### 字典推导式

>>> words = 'rocky like python'
>>> letter_cnt = {letter:words.count(letter) for letter in words}
>>> letter_cnt
{'r': 1, 'o': 2, 'c': 1, 'k': 2, 'y': 2, ' ': 2, 'l': 1, 'i': 1, 'e': 1, 'p': 1, 't': 1, 'h': 1, 'n': 1}

### 集合推导式

>>> my_set = {i for i in range(0,6) if i % 3 == 1}
>>> my_set
{1, 4}

### 生成器推导式

>>> my_exp = (i for i in range(0,6))
>>> my_exp
<generator object <genexpr> at 0x110090308>
>>> type(my_exp)
<class ‘generator'>

>>> for exp in my_exp:
...    print(exp)
...
0
1
2
3
4
5

>>> second_exp = list(my_exp)
>>> second_exp
[]