Files
Python_CookBook_repo/4.迭代器与生成器/3.使用生成器创建新的迭代模式.py
2025-09-10 16:12:45 +08:00

53 lines
1.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

if __name__ == '__main__':
def fbb(start, stop, step):
x = start
while x <= stop:
yield x
x += step
# 上面是一个生成器函数,它只会在相应迭代时运行
# 在调用生成器函数的时候,因为直接生成了数字,所以有返回值
for i in fbb(0, 10, 1):
print(i)
# 尝试使用fbb生成金字塔
# 先用生成器整一个斐波那契数列生成函数
def fbb_arr(n):
index = 0
a0 = 1
a1 = 1
while index < n:
yield a0
a0, a1 = a1, a0 + a1
index += 1
# 按照n行打印出来
def print_num_delta(n):
# 计算需要生成多少个数字
fbb_number_num = sum(range(1, n + 1))
# 生成数字并保存
fbb_list = list(fbb_arr(fbb_number_num))
# 数字下标,用于遍历中保存位置
start_index = 0
# 每一行的数字数量
for number_num in range(1, n + 1):
# 切片用空格分隔后转成字符串
nums = ' '.join(str(item) for item in fbb_list[start_index: start_index + number_num])
# 格式化打印
print(format(nums, r' ^{}'.format(len(str(fbb_list[-1])) * n)))
# 更新下一行的数字下标
start_index = start_index + number_num
print_num_delta(5)
# 生成器里为什么没有return: 如果一个函数里包含yield语句那就会被识别为生成器函数
# 函数里的return此时自动失效被替换成生成器
# 生成器函数在识别到return时意识到生成结束返回的StopIteration交给for识别