zoukankan      html  css  js  c++  java
  • python 笔记3--高级特性

    切片

    语法

    • L[l:r] 取L[l],L[l+1]…L[r-2],L[r-1]
    • L[l:r:m] 取L[l],L[l+m],L[l+2*m],L[l+3*m]….(满足l+n*m<=r-1)

    tips

    • 字符串,tuple也可以切片

    迭代

    dict

    • 迭代key
    >>> for key in d:
            print(key)
    • 迭代value
    for value in d.values()
    • 迭代key和value
    for value,key in d.items():
        print(value,key)

    字符串

    • 语法
    >>> for ch in 'ABC':
    ...     print(ch)

    判断是否属于迭代对象

    >>> from collections import Iterable
    >>> isinstance('abc', Iterable) # str是否可迭代
    True
    >>> isinstance([1,2,3], Iterable) # list是否可迭代
    True
    >>> isinstance(123, Iterable) # 整数是否可迭代
    False

    调用索引-元素(enumerate)

    >>> for i, value in enumerate(['A', 'B', 'C']):
    ...     print(i, value)
    ...
    0 A
    1 B 
    2 C
    

    引用两个变量

    >>> for x, y in [(1, 1), (2, 4), (3, 9)]:
    ...     print(x, y)
    ...
    1 1
    2 4
    3 9

    列表生成器

    普通list

    list(range(1, 11))
    或者循环型
    [m for m in list(range(1,11))]

    多重循环

    >>> [m + n for m in 'ABC' for n in 'XYZ']
    ['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']

    带判断语句

    [x * x for x in range(1, 11) if x % 2 == 0]
    [4, 16, 36, 64, 100]
    
    //isinstance 判断一个变量是否是某个类型
    ['Hello', 'World', 18, 'Apple', None]
    [s.lower() if isinstance(s,str) else s for s in L]
    ['hello', 'world', 18, 'apple', None]

    生成器

    -普通的generator
    (x * x for x in range(10))
    - 函数 generator

    def fib(max):
        n, a, b = 0, 0, 1
        while n < max:
            yield b
            a, b = b, a + b
            n = n + 1
        return 'done' 

    原理:
    这里,最难理解的就是generator和函数的执行流程不一样。函数是顺序执行,遇到return语句或者最后一行函数语句就返回。而变成generator的函数,在每次调用next()的时候执行,遇到yield语句返回,再次执行时从上次返回的yield语句处继续执行。

    • 捕获return
      比较麻烦,暂时不理

    小作业

    杨辉三角的generator
    
    def triangle(n):
        L=[1]
        while True:
            yield(L)
            L.append(0)
            L=[L[i]+L[i-1] for i in range(len(L))]
            if len(L)>n:
                return "done"
    
    g=triangle(100)
    for i in g:
        print(i)

    这一句比较奇异,L全部计算完后才赋值给原来的L。
    L=[L[i]+L[i-1] for i in range(len(L))]

    迭代器

    小结
    凡是可作用于for循环的对象都是Iterable类型;
    是可作用于next()函数的对象都是Iterator类型,它们表示一个惰性计的序列;
    集合数据类型如list、dict、str等是Iterable但不是Iterator,不过可以通过iter()函数获得一个Iterator对象。

  • 相关阅读:
    DRF
    DRF
    DRF
    DRF
    DRF
    DRF
    DRF
    Mongo错误记录:MongoClient opened before fork. Create MongoClient
    Hive默认分隔符和默认NULL值
    hdfs文件格式比较
  • 原文地址:https://www.cnblogs.com/zy691357966/p/5480319.html
Copyright © 2011-2022 走看看