美文网首页python cook
python cookbook学习笔记01

python cookbook学习笔记01

作者: 淡若s清茶 | 来源:发表于2018-08-07 17:44 被阅读0次

    python cookbook一些知识点

    一、python数据结构与算法

    1. python解压赋值
    data = ['ACME', 50, 91.1, (2012, 12, 21)]
    name, shares, *price = data
    print(price)
    a1, b1, c1, (d1, e1, f1) = data
    print(d1, f1)
    
    
    1. 字符解压赋值
    data = "hello"
    a, *b, c = data
    print(c)
    结果:o
    
    1. 占位可以用_,解压多个值可用*
    _, *b1, c1, d1 = data
    print(b1)
    
    1. 解压多个值,好用的方法
    records = [
        ["foo", 1, 2],
        ["fo", 1],
        ["foo", 3, 4],
    ]
    def fn(x, y):
        print("foo", x, y)
    for flag, *l in records:
        if flag == "foo":
            x, y = l
            fn(x, y)
    
    1. 解压赋值,双\ 代表转义
    str_r = r"H:\Sublime\User\GoSublime\windows-x32"
    a, *b, c = str_r.split("\\")
    print(a, c)
    
    
    1. 有长度队列,pop后进先出
    from collections import deque
    q = deque(maxlen=3)
    q.append(1)
    q.append(2)
    q.append(3)
    q.append(4)
    q.pop()
    q.appendleft(6) #在右边增加
    
    1. 查找n最大最小值
    import heapq
    list_a = [1, 6, 7, 3, 5, 8, 3]
    print(heapq.nlargest(3, list_a))
    print(heapq.nsmallest(3, list_a))
    print(heapq.nlargest(len(list_a), list_a))
    
    import heapq
    portfolio = [
        {'name': 'IBM', 'shares': 100, 'price': 91.1},
        {'name': 'AAPL', 'shares': 50, 'price': 543.22},
        {'name': 'FB', 'shares': 200, 'price': 21.09},
        {'name': 'HPQ', 'shares': 35, 'price': 31.75},
        {'name': 'YHOO', 'shares': 45, 'price': 16.35},
        {'name': 'ACME', 'shares': 75, 'price': 115.65}
    ]
    print(heapq.nlargest(3, portfolio, key=lambda i: i["shares"]))
    
    堆排序 会把最小元素提到最前面
    import heapq
    list_a = [1, 6, 7, 3, 5, 8, 3, -2, -3, -1]
    heapq.heapify(list_a)
    print(list_a)
    扔掉最前面一个元素
    heapq.heappop(list_a)
    print(list_a)
    heapq.heappop(list_a)
    print(list_a)
    heapq.heappop(list_a)
    扔掉最小元素
    print(heapq.heappop(list_a))
    print(list_a)
    
    1. 多映射值dict的创建
    from collections import defaultdict
    d = defaultdict(set)
    d["a"].add(1)
    d["a"].add(2)
    d['b'].add(1)
    d['b'].add(1)
    print(d)
    print(d["a"])
    
    1. 有序字典的创建
    from collections import OrderedDict
    od = OrderedDict()
    od["three"] = 3
    od["four"] = 4
    od["one"] = 1
    od["two"] = 2
    print(od)
    有序字典,不过内存消耗大
    

    相关文章

      网友评论

        本文标题:python cookbook学习笔记01

        本文链接:https://www.haomeiwen.com/subject/vmbavftx.html