# Python 强化训练：第三篇

## 问题来源

1. pythoner面试经常会问到迭代器和生成器的区别

## 内容

1. 可迭代对象
2. 迭代器：正向迭代, 反向迭代
3. 生成器：

### 1.

for 语句对对象调用了 iter()方法, 使用next()方法

```for element in [1, 2, 3]:
print(element)

for element in "abcdef":
print(element)

for key in {"one": 1, "two": 2}:
print(key)```

dir(str)

dir(dict)

dir(list)

```实现可迭代对象, 可迭代对象实现迭代器对象

from collections import  Iterable, Iterator

class RangeInt(Iterator):

def __init__(self, start, end, step):
self.start = start
self.end = end
self.step = step

def __next__(self):
if self.start > self.end:
raise StopIteration
t = self.start
self.start += self.step
return t

class RangeInt_Iterable(Iterable):

def __init__(self, start, end, step):
self.start = start
self.end = end
self.step = step

def __iter__(self):
return RangeInt(self.start, self.end, self.step)

for i in RangeInt_Iterable(0, 10, 1):
print(i)```

## 2.

```返回区间内的素数

class NumBer(object):

def __init__(self,  start, end):
self.start = start
self.end = end

def isshu(self, k):
if k < 2:
return False

for i in range(2, k):
if k % i == 0:
return False

return True

def __iter__(self):
for j in range(self.start, self.end):
if self.isshu(j):
yield j

number = NumBer(0, 100)
for i in number:
print(i)```

````a = (i for i in range(5))`
`type(a)# class 'generator'````

````b = [i for i in range(5)]`
`type(b)# class list````

````c= {k:randint(10,20) for k in "xyzabc"}`
`type(c)# class dict````

````e = {j for j in range(5)}`
`type(e)# class set````

## 3.

L = list(range(5))

```如何反向迭代：

for i in L.reverse():
print (i) # L被反向

for i in L[::-1]:
print(i) # 创建 一个新的list

for i in reversed(L):
print(i)```

`__reversed__`接口

```class FloatRange:
def __init__(self, start, end, step=0.1):
self.start = start
self.end = end
self.step = step

def __iter__(self):
t = self.start
while t <= self.end:
yield t
t += self.step

def __reversed__(self):
t = self.end
while t >= self.start:
yield t
t -= self.step

for x in reversed(FloatRange(1.0, 4.0, 0.5)):
print x```

114 篇文章44 人订阅

0 条评论

## 相关文章

### 【Go 语言社区】Go语言数组

Go编程语言提供称为数组的数据结构，其可存储相同类型的元素的一个固定大小的连续集合。数组用于存储数据的集合，但它往往是更加有用认为数组作为相同类型的变量的集合。...

364150

14830

610100

48150

### Python内置函数sorted()从入门到精通

Python内置函数sorted()可以对列表、元组、字典、集合、字符串、range对象以及其他可迭代对象进行排序，返回排序后的列表，支持使用key参数指定排序...

282100

314100

28550

6410

11120

25060