# 深入浅析Python中的迭代器

``` contents structure [-] ```

## 1. Iterator VS Iterable

```
a_set = {1, 2, 3}#定义set数据类型，set是可迭代类型
b_iterator = iter(a_set)#得到set的迭代器
#Output: 1
print(next(b_iterator))
#Output:

print(type(a_set))
#Output:

print(type(b_iterator))

```

```
class Series(object):
def __init__(self, low, high):
self.current = low
self.high = high
def __iter__(self):
return self
def __next__(self):
if self.current > self.high:
raise StopIteration
else:
self.current += 1
return self.current - 1
n_list = Series(1,10)
print(list(n_list))
```

## 2.Itertools 模块

Itertools是Python的内置模块，其中包含了能够创建迭代器的函数。简而言之，它提供了许多能够与迭代器交互的方法。

```
from itertools import count
sequence = count(start=0, step=1)
while(next(sequence) <= 10):
print(next(sequence),end=" ")
```

Itertools中的cycle函数可以创建无限迭代器，例如：

```
from itertools import cycle
dessert = cycle(['Icecream','Cake'])
count = 0
while(count != 4):
print('Q. What do we have for dessert? A: ' + next(dessert))
count+=1
```

Q. What do we have for dessert? A: Icecream
Q. What do we have for dessert? A: Cake
Q. What do we have for dessert? A: Icecream
Q. What do we have for dessert? A: Cake

## 3.生成器（Generator）

```
def series_generator(low, high):
while low <= high:
yield low
low += 1
n_list = []
for num in series_generator(1,10):
n_list.append(num)
print(n_list)
```

```
def test():
print("进入test函数")
for i in range(2):
print("yield number ",i)
yield i
if "__main__" == __name__:
print("开始调用test")
res = test()
print("结束调用test")
next(res)
next(res)
```

yield number 0

yield number  1

python中生成器可以分为生成器函数和生成器表达式，生成器函数和生成器表达式是两种不同的类型。

```
squares = (x * x for x in range(1,10))
print(type(squares))
print(list(squares))
```

[1, 4, 9, 16, 25, 36, 49, 64, 81]

https://www.datacamp.com/community/tutorials/python-iterator-tutorial

QQ号联系： 360901061

【本文对您有帮助就好】