Python中什么时候会用到生成器?

发布时间 2023-08-29 11:08:31作者: 山雨欲來風滿楼

示例:

我:帮我写一个Python的生成器的示例:

AI:当然可以!以下是一个简单的示例,生成器函数用于生成一个范围内的偶数:

def even_numbers(start, end):
    current = start
    while current <= end:
        if current % 2 == 0:
            yield current
        current += 1

start_num = int(input("请输入起始数字:"))
end_num = int(input("请输入结束数字:"))

numbers = even_numbers(start_num, end_num)
for num in numbers:
    print(num)

在这个示例中,我们定义了一个名为`even_numbers`的生成器函数,它接受两个参数`start`和`end`,表示生成偶数的范围。在生成器函数内部,我们使用`yield`关键字来生成偶数。然后,我们通过在`for`循环中迭代生成器对象`numbers`来打印生成的偶数。

你可以根据需要修改`start_num`和`end_num`的值来生成不同范围内的偶数。

===============

redis中用

def hscan_iter(self,name,match=None,count=None):
    """
    Make an iterator using the HSCAN command so that client doesn't need to remember the cursor position.
    制作一个生成器,使用HSCAN的命令,以便客户端不需要记住当前游标的位置。
    ``match`` allows for filtering the keys by pattern
    match关键字参数,是用来匹配筛选。
    ``count`` allows for hint the minimum number of returns
    count关键字参数,允许提示每次返回最小数量。
    """
    cursor='0'	# 注意这个'0'是字符串的0
    while cursor!=0:
        cursor,data = self.hscan(name,cursor=cursor,match=match,count=count)
        for item in data.items():	
            yield item

 

 

【扩展】:Python三大特性:装饰器,生成器,迭代器。