【Python3 笔记】Python3 的高级特性 切片、迭代、列表生成式、生成器、迭代器

本系列是学习 廖雪峰 Python3 教程 过程中记录的笔记,本篇文章记录 Python 的一些高级特性,包括切片操作、迭代操作、列表生成式的使用,以及生成器和迭代器。

高级特性

切片

  • 适用于 List Tuple 和字符串,操作灵活;

  • [start_index : end_index : step_size]

    省略 start_index ,包含该索引,默认从 0 开始;

    省略 end_index , 不包含该索引,默认到最后一位截至;

    省略 step_size ,默认步长为 1 ;

    L = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    print(L[0:2])
    print(L[0:6:2])
    print(L[0:6:3])
    print(L[-4:-1])
    print(L[-4:-1:2])
    print(L[::])
    
    output————————
    [0, 1]
    [0, 2, 4]
    [0, 3]
    [6, 7, 8]
    [6, 8]
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    

迭代

  • 适用于所有可迭代对象,常见的数据类型有 List Tuple Dict Set 和 字符串,对于 Tuple Dict 由于元素无序,迭代出的结果很可能也是无序的。

  • for value in dict.values() 访问所有的 value

  • for k, v in dict.items() 可同时访问 keyvalue

  • for i, value in enumerate(list) 可同时访问 indexvalue

    d = {'a': 1, 'b': 2, 'c': 3}
    for value in d.values():    
        print(value)
        
    for key, value in d.items():    
        print(key, ":", value)
        
    L = ["wang", "tian", "liang"]
    for index, value in enumerate(L):    
        print(index, ":", value)
        
    str = "i love u"
    for ch in str:
        print(ch)
    
    output————————
    1
    2
    3
    a : 1
    b : 2
    c : 3
    0 : wang
    1 : tian
    2 : liang
    i
     
    l
    o
    v
    e
     
    u
    

列表生成式

  • range(start_index, end_index, step_size) 返回整数列表;

  • [x * y for x in range(0, 6, 5) for y in range(1, 3)] 基本上两层循环就可以满足绝大部分需求了,简化代码;

  • [x for x in range(0, 5) if x % 2 == 0] 生成式中的 if 用于筛选合适的值;

  • 生成式中还可以与 d.items() 内置函数等结合;

    L = [x * y for x in range(0, 6, 5) for y in range(1, 3)]
    print(L)
    
    L = [x for x in range(0, 5) if x % 2 == 0]
    print(L)
    
    d = {'x': 'A', 'y': 'B', 'z': 'C'}
    L = [k + '=' + v for k, v in d.items()]
    print(L)
    
    L = ['Hello', 'World', 'IBM', 'Apple']
    l = [s.lower() for s in L]
    print(l)
    
    output————————
    [0, 0, 5, 10]
    [0, 2, 4]
    ['x=A', 'y=B', 'z=C']
    ['hello', 'world', 'ibm', 'apple']
    

生成器

  • 一边循环一边计算的机制,可以节省大量空间;

  • 列表生成器,仅需要将 [] 换成 () 即可,使用 for 循环迭代访问,也可以使用 next() 依次访问;

  • 函数生成器,带有 yield 关键字,此时调用该函数时需要先生成一个函数对象,每次使用 next() 执行,遇到 yield 就中断执行,下次执行时从上次中断位置继续;

  • 函数生成器的返回值包含在 StopIteration 错误的 value 中。

    g = (x * x for x in range(3))
    print(type(g))
    for n in g:
        print(n)
    
    def fib(max):       # 斐波拉契数列生成器
        n, a, b = 0, 0, 1
        while n < max:
            yield b
            a, b = b, a + b
            n = n + 1
        return 'done'
    
    g = fib(4)
    while True:
        try:
            x = next(g)
            print('g:', x)
        except StopIteration as e:
            print('Generator return value:', e.value)
            break
    
    output——————————
    <class 'generator'>
    0
    1
    4
    g: 1
    g: 1
    g: 2
    g: 3
    Generator return value: done
    

迭代器

  • 凡是可作用于for循环的对象都是Iterable类型,使用isinstance()判断一个对象是否是Iterable对象;

  • 凡是可作用于next()函数的对象都是Iterator类型,它们表示一个惰性计算的序列;

  • 集合数据类型如listdictstr等是Iterable但不是Iterator,不过可以通过iter()函数获得一个Iterator对象;

  • 非迭代器的可迭代对象在使用for循环时,实际是先调用 iter() 方法转换为迭代器,再循环调用 next()并返回值。

    from collections import Iterable
    print(isinstance([], Iterable))
    print(isinstance({}, Iterable))
    print(isinstance((), Iterable))
    print(isinstance('abcd', Iterable))
    print(isinstance(100, Iterable))
    
    for x in [3, 4, 5]:
        print(x)
    
    it = iter([3, 4, 5])      		# 首先获得Iterator对象
    while True:
        try:
            x = next(it)            # 获得下一个值
            print("iter:", x)
        except StopIteration:       # 遇到StopIteration就退出循环
            break
            
    output———————————
    True
    True
    True
    True
    False
    3
    4
    5
    iter: 3
    iter: 4
    iter: 5
    
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值