• for、while循环


    for循环

    复制代码
    # for 循环后面可以对Iterable或者Iterator进行遍历
    # "abc"和[1,2,3]为可迭代对象,range(4)为迭代器
    for i in "abc":   
        print(i)  # a b c
    for i in [1,2,3]:  
        print(i)  # 1 2 3
    for i in range(4):
        print(i)
    复制代码

    Iterable和Iterator区别

    Iterable是知道长度的。例如list, tuple,str,dict 

    Iterator是个地址,调用一个next()就走一步,是惰性的

    判断Iterable和Iterator

    迭代器一定是可迭代对象,反过来不一定成立

    from collections import Iterable
    from collections import Iterator
    a = [1,2,3,4]
    print(isinstance(a,Iterable))  # 判断a是不是可迭代对象,True
    b = (i for i in range(10))
    print(isinstance(b, Iterator)) # 判断b是不是迭代器,True

     扩展:迭代器和生成器的区别?(生成器是创建迭代器的一种方式)

    创建迭代器的三种方式之一:重写__iter__和__next__方法

    复制代码
    class Container(object):
        def __init__(self,start,end):
            self.start = start
            self.end = end
        def __iter__(self): # 重写__iter__方法
            return self
        def __next__(self): # 重写__next__方法
            if self.start < self.end:
                i = self.start
                self.start += 1
                return i
            else:
                raise StopIteration()
    
    for i in Container(0,6): # 容器Container是一个迭代器
        print(i)
    # 输出 0 1 2 3 4 5
    复制代码

    创建迭代器的三种方式之二:内置函数iter()将Iterable转换为Iterator

    i = "abcde"
    itor = iter(i)
    print(type(itor))      # <class 'str_iterator'>
    print(itor.__next__()) # a

    创建迭代器的三种方式之三:生成器通过 yield语句快速生成迭代器,省略了复杂的 __iter__() & __next__() 

    下面代码可以看出生成器可以用调用迭代器的方式去遍历

    复制代码
    def container(start, end):
        while start < end:
            yield start;
            start += 1;
    
    for i in container(1,7):
        print(i)       # 1 2 3 4 5 6
    复制代码

    也可以用这种方式遍历生成器

    c  = container(1,7)
    while True:
        try:
            print(c.__next__());
        except StopIteration as e:
            break;

    扩展:yield在Python3.5以后的新特性:

    while循环无限次

    复制代码
    while true:
    
        ...
    
    else:     #后面可以跟else   表示上面的循环结束就执行else中的内容
    
                ...
    复制代码
  • 相关阅读:
    【POJ 3525】Most Distant Point from the Sea(直线平移、半平面交)
    【HDU 4940】Destroy Transportation system(无源无汇带上下界可行流)
    codevs 5962 [SDOI2017]数字表格
    【NOIP2016】天天爱跑步
    [2011WorldFinal]Chips Challenge[流量平衡]
    [Ahoi2014]支线剧情[无源汇有下界最小费用可行流]
    [NOI2008] 志愿者招募[流量平衡]
    [Wc2007]剪刀石头布[补集转化+拆边]
    poj3281 Dining[最大流]
    1458: 士兵占领[最大流]
  • 原文地址:https://www.cnblogs.com/revo/p/9271850.html
Copyright © 2020-2023  润新知