python迭代器和生成器

迭代器:

迭代器是一种数据流,可以进行迭代(循环),每次返回一个数据

生成器:

生成迭代器的函数就是生成器

比如:

def my_range(x):
    i = 0
    while i < x:
        yield i
        i += 1

my_iterator = my_range(5)

for x in my_iterator:
    print(x)

0
1
2
3
4

上面这段代码里的 my_range 就是生成器,  my_iterator 就是生成的迭代器, 可以循环迭代器.

生成器使用关键字  yield  ,  yield 的值就是迭代器的数据流,每次调用时都用停下的位置继续,直到生成器函数退出,数据流生成完毕.

一些栗子:

# 将lessons列表转换为一个数据流,数据流的每一项是一个tuple,tuple的第一个值是数字,当前是第几课,第二个值是lessons里对应的值,就是课名.

lessons = ["Why Python Programming", "Data Types and Operators", "Control Flow", "Functions", "Scripting"] def my_enumerate(iterable, start=0): # iterable是一个list index = 0 # 循环iterable对象 while index < len(iterable): # start的第几课,index是列表的索引 yield (start, iterable[index]) index += 1 start += 1 for i, lesson in my_enumerate(lessons, 1): print("Lesson {}: {}".format(i, lesson))
Lesson 1: Why Python Programming
Lesson 2: Data Types and Operators
Lesson 3: Control Flow
Lesson 4: Functions
Lesson 5: Scripting
# 将iterable对象拆成若干个列表的数据流,每个列表的长度为指定的size

def
chunker(iterable, size): # 循环的间隔是size for i in range(0, len(iterable), size): yield iterable[i:i + size] for chunk in chunker(range(25), 4): print(list(chunk))
[0, 1, 2, 3]
[4, 5, 6, 7]
[8, 9, 10, 11]
[12, 13, 14, 15]
[16, 17, 18, 19]
[20, 21, 22, 23]
[24]

range 方法的第三个参数表示循环的间隔,如果不设置,默认是1,就是从开始到结束,0,1,2,3,4...那样循环.如果设置为3,就是一次间隔为3, 就是0,3,6,9...那样循环

猜你喜欢

转载自www.cnblogs.com/liulangmao/p/9142777.html