• 数据结构及算法(1)


    1.将序列分解为单独的变量

    C:UsersPIS>python
    Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:54:40) [MSC v.1900 64 bit (AMD64)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>> a = [3,4]
    >>> b,c=a
    >>> b
    3
    >>> c
    4

    如果元素的数量不匹配,将得到一个错误的提示。

    实际上不仅仅是元组或列表,只要对象是可迭代的,那么就可以执行分解操作,这包括字符串,文件,迭代器和生成器。

    以文件为例

    C:UsersPIS>cd.>1.txt
    
    C:UsersPIS>echo hello >1.txt
    
    C:UsersPIS>echo world >>1.txt
    
    C:UsersPIS>type 1.txt
    hello
    world
    
    C:UsersPIS>python
    Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:54:40) [MSC v.1900 64 bit (AMD64)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>> a=open("1.txt", "r")
    >>> b,c =a
    >>> b
    'hello 
    '
    >>> c
    'world 
    '
    >>>
    

     实际上,文件对象就是一个迭代器。

    2 从任意长度的可迭代对象中分解元素

    >>> a=[1,2,3,4,5]
    >>> b,c,*d=a
    >>> b
    1
    >>> c
    2
    >>> d
    [3, 4, 5]
    

      注意同级只能出现一个*,不然语法错误。

    利用“*”的巧妙的递归算法

    def sum(items):
        head,*tail = items
        return head + sum(tail) if tail else head
    items = [1,2,4]
    sum(items)
    

      理论上在函数递归调用的过程中不会存在栈空间过大占用,因为函数return后已脱离此级函数,但是目前python没有语法的优化,有某一个调用限制。试试items=range(10000)

    3 保存最后N个元素

    在迭代操作或者其他操作的时候,怎样只保留最后有限几个元素的历史记录?

    保留有限历史记录正是collections.deque大显身手的时候。比如,下面的代码在多行上面做简单的文本匹配, 并只返回在前N行中匹配成功的行:

    from collections import deque
    
    def search(lines,pattern,history=5):
        previous_lines = deque(maxlen=history)
        for li in lines:
            if pattern in li:
                yield li,previous_lines
            previous_lines.append(li)
    
    if __name__ == "__main__":
        with open(r"whateverdir","r") as f:
            for line, prevlines in search(f, "python", 5):
                for pline in prevlines:
                    print(pline,  end='')
                print(line, end='')
                print('_'*20)
    

     对deque不了解的请查看相关文档。

    从队列两端添加或弹出元素的复杂度都是O(1)。这和列表不同,当从列表的头部插入或移除元素时,列表的复杂度为O(N)。

  • 相关阅读:
    何为 ISAPI
    MacDown-The open source Markdown editor for OS X.
    Atom使用
    运维
    Perl
    Kaggle
    J2EE
    leetcode
    Tensorflow 学习笔记
    EXCEL公式及宏
  • 原文地址:https://www.cnblogs.com/MY0213/p/8673467.html
Copyright © 2020-2023  润新知