1. 程式人生 > >簡單資料結構

簡單資料結構

  • 排列組合

    import itertools
    ​
    # 排列:從m個元素中提取n個,所有可能就是排列(有順序)
    # 當m等於n時的排列稱為全排列
    # it = itertools.permutations([1, 2, 3], 3)
    # 組合:沒有順序的排列
    # it = itertools.combinations([1, 2, 3, 4], 2)
    # 笛卡爾乘積:多個序列中的元素組合
    # it = itertools.product([1, 2], [3, 4], [5, 6])
    # 上面多個相同序列的場景
    it = itertools.product([1, 2], repeat=3)
    ​
    
    print(it) for i in it: print(i) ​ # 可以轉換為列表 # print(list(it1))
  • 計數器及雙向佇列

    from collections import Counter, deque
    ​
    # 統計序列中元素出現的次數
    c = Counter([1, 2, 3, 4, 1, 2, 3, 1, 2, 1])
    ​
    print(c)
    print(type(c))
    # 可以轉換為字典
    print(dict(c))
    ​
    # 雙向佇列
    d = deque([1, 2, 3])
    ​
    # 右側追加
    d.append(4)
    # 左側新增
    d.appendleft(5) ​ # 右側彈出資料 print(d.pop()) # 左側彈出資料 print(d.popleft()) ​ # 右側擴充套件 d.extend(['a', 'b', 'c']) # 左側擴充套件 d.extendleft(['aa', 'bb', 'cc']) ​ # 迴圈移動:正數表示向右移動,負數表示向左移動 # d.rotate(1) d.rotate(-1) print(d) print(list(d))
  • 連結串列

    • 新增節點

    • 追加節點

    • 插入節點

    • 刪除節點