Skip to content

Latest commit

 

History

History
84 lines (59 loc) · 7.59 KB

File metadata and controls

84 lines (59 loc) · 7.59 KB
title
Python / Data Structure

Python / Data Structure

基礎

Sequence ??

List??

Mapping??

  • Mapping Types — dict - 5. Built-in Types — Python 2.7.14 documentation #ril
    • 所謂 mapping object 是 hashable -> object 的對照 (只有 key 一定要是 hashable),目前 standard library 裡只有一個 mapping type -- dictionary (dict)。
    • 除了用 {key: value, ...} 建立之外,還有 dict(**kwarg)dict(mapping, **kwarg)dict(iterable, **kwarg) 3 種 contructor -- 其中 positional argument 跟 keyword arguments 都是 optional,兩者的關係是 "先根據 positional argument 建立基礎的 dict (如果沒有就是 empty),然後再用 keyword arguments 覆寫 (但 key 必須是合法的 Python identifier)。其中 positional argument 若是 mapping,會把 key-value pairs 抄寫過來,若是 iterable,每個 item 都必須是長度為 2 的 iterable -- 分別是 key 跟 value。
    • 例如 {'one': 1, 'two': 2, 'three': 3} 等同於 dict(one=1, two=2, three=3)dict(zip(['one', 'two', 'three'], [1, 2, 3]))dict([('two', 2), ('one', 1), ('three', 3)])dict({'three': 3, 'one': 1, 'two': 2})
    • dict.items() 提到 "CPython implementation detail: Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions.",這裡 "in an arbitrary order & is non-random" 的說法很特別,在單元測試時要如何準備資料,來驗證邏輯裡有自己做排序,而不是相依於 CPython impl. 內部實作? 透過 code review? 或是用 assert 檢查預設的順序跟排序的結果不同?
  • 5.5. Dictionaries - 5. Data Structures — Python 2.7.14 documentation #ril

Ordered Mapping ??

Set??

map() ??

  • Getting a map() to return a list in Python 3.x - Stack Overflow map(chr, [66, 53, 0, 94]) 在 Pyhton 2.6 會傳回 list,但在 Python 3 會傳回 map object?
    • Triptych: 在 Python 3 許多對 iterable 的處理也回傳 iterator,這樣的可以節省記憶體、加快處理。如果要做 iteration,直接用 for loop (例如 for ch in map(chr,[65,66,67,68])) 就可以,不用先轉為 list。
  • Python 2 map(chr, map(ord, 'Hello')) 會得到 ['H', 'e', 'l', 'l', 'o'],但 map(chr, map(ord, 'Hello')) 會得到一個 <map object at ...>,是個 iterator。可以用 list()tuple() 轉換成 list/tuple

排序 (Sorting)??

def test_sorting__sorted():
    versions = ['10.0.01', '11.3.00', '9.8.12', '9.8.00']
    assert sorted(versions, key=lambda v: map(int, v.split('.'))) == \
        ['9.8.00', '9.8.12', '10.0.01', '11.3.00']

def test_sorting__sort_in_place():
    versions = ['10.0.01', '11.3.00', '9.8.12', '9.8.00']
    versions.sort(key=lambda v: map(int, v.split('.')))

    assert versions == ['9.8.00', '9.8.12', '10.0.01', '11.3.00']

參考資料:

map()、filter()、any()、all()、zip() 的妙用??

  • [expression for item in iterable] == map(lambda item: expression, iterable)

如何實現 immutable list??

參考資料 {: #reference }