python可迭代,迭代器,生成器,装饰器

可迭代:是指可以使用for循环迭代的对象

可迭代(Iterable):  常见的可迭代对象包括列表(list),元组(tuple),字典(dict),集合(set)生成器(generator)

列表:

my_list = [1,2,3,4,5]
for i in my_list:
    print(i)
#列表是可迭代的对象

元组:

my_tuple = (1,2,3,4,5)
for i in my_tuple:
    print(i)

字典

my_dict = {
    "value1":1,
    "value2":2
}
for k, v in my_dict.items():
    print(k, v)
#结果以键值对的形式输出 value1 1   value2 2

集合

my_set = {1,2,3,4,5}
for i in my_set:
    print(i)

迭代器(Iterator):主要有两个方法__iter__(), __next__()

__iter__()返回迭代器对象本身

__next__()该方法返回迭代器中的下一个元素

自定义迭代器类:

class MyDatas:
    def __init__(self, n):
        self.datas = [i for i in range(1, n + 1)] #创建一个1-n的整数列表
        self.current_index = 0 #初始化当前索引为0

    def __iter__(self):
        return self  #返回迭代器自身,这里指的是MyDatas

    def __next__(self):
        if self.current_index >= len(self.datas): #判断索引长度是否超过列表
            raise IndexError("超出范围") #超出则抛出异常
        else:
            current = self.datas[self.current_index] #否则获取当前索引对应的元素
            self.current_index += 1 #更新索引,进行下一次迭代
            return current #返回当前索引的元素


md = MyDatas(5) #创建实例
print(next(md))#调用next函数,输出下一个元素
print(next(md))#接着上一次数次,继续调用next函数,输出
print(next(md))
print(next(md))
print(next(md))
print(next(md))

结果:前面五个next正常输出,第六个已经超出列表长度,抛出异常IndexError

生成器:yield是生成器的关键字,它可以在迭代过程中逐步返回值,而不是一次返回所有的值

下面通过在函数内部使用yield关键字定义了一个生成器函数,调用时,函数会在每个yeile语句处暂停并返回一个值,下次调用接着执行

def gen_func(x):
    for x in range(x):
        yield x
f=gen_func(5)
print(f) #<generator object gen_func at 0x0000019A1355D7E0>
print(next(f))# 0
print(next(f))# 1

装饰器:在不改变函数原来实现的基础上,为函数增加额外的功能

下面是一个随机生成1万个1-10万的随机数,并使用装饰器计算两个表所消耗的时间

使用原写法可以得到,但我们将它换成l更为方便的装饰器"@装饰器名"

datas = [random.randint(1, 100000) for i in range(10000)]
copy_datas = datas.copy()


def cost_time(f):
    def calc():
        start = time.time()
        f()
        print(f"生成的时间消耗为:{time.time() - start}")

    return calc

@cost_time
def my_fun1():
    datas.sort(reverse=True)
    print(datas)


# my_fun1 = cost_time(my_fun1) #原写法
my_fun1()

@cost_time
def my_fun2():
    new_datas = sorted(datas.copy(), reverse=True)
    print(new_datas)
# my_fun2 = cost_time(my_fun2) #原写法
my_fun2()

  • 9
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值