阅读量:0
- 使用range()函数生成指定范围的数字序列:
def generate_numbers(n): for i in range(n): yield i for num in generate_numbers(5): print(num)
- 使用列表推导式生成列表:
numbers = [x for x in range(5)] for num in numbers: print(num)
- 使用条件表达式过滤元素:
def generate_numbers(n): for i in range(n): if i % 2 == 0: yield i for num in generate_numbers(5): print(num)
- 使用嵌套循环生成多重循环序列:
def generate_pairs(): for i in range(3): for j in range(3): yield (i, j) for pair in generate_pairs(): print(pair)
- 使用zip()函数将多个生成器合并成一个:
def generate_letters(): yield from 'abc' def generate_numbers(): yield from range(1, 4) for letter, number in zip(generate_letters(), generate_numbers()): print(letter, number)