Python :リスト対辞書


Pythonには複数の種類のデータ構造があり、それらのリストと辞書はその一つです.そこでここではどの条件で効率的なのかについて議論しています.
まず、両方について紹介します.

リスト:


インパイソンlist の順序を格納する最も汎用的なデータ構造ですobjects 異なるtypes .
インパイソンlist are mutable , つまり、これらの要素はstr or tuple . これらelements リストのitems .
フォークリエイトlist Pythonでは、多くの方法がありますが、これを行う最も簡単な方法は[ ] で区切った項目を, .
リストの作成方法
  • 空のリストを示すために四角いブラケットのペアを使用すること.
  • 四角形のブラケットを使って、項目をコンマで区切ってください.
  • リスト理解の使用
  • 型コンストラクタの使用.
  • a = [] # provide empty list
    b = [1,2,3] 
    c = [x for x in iterable]
    d = list('abc')
    e = list((1,2,3))
    

    辞書


    インパイソンdictionary マッピングオブジェクトマップhashablearbitrary オブジェクト.それはPythonのMapping type そして、1つの標準mapping 種類dictionary . またmutable . Pythondictionarykey , value ペアkeys はほとんど任意であり、Hashable 値を含むlist , dictionary などmutable タイプはkeys インdictionary .

    Numeric types used for keys obey the normal rules for numeric comparison: if two numbers compare equal (such as 1 and 1.0) then they can be used interchangeably to index the same dictionary entry.


    としてlists , 辞書は様々な方法で作成することができますが、それを作成する最も簡単な方法は: 分離ペアkeys and values インサイド{ } .
    辞書の作成方法
  • キーのコンマ区切りのリストを使用します.
  • dictの理解を使用します.
  • 型コンストラクタを使用します.
  • a = dict(one=1, two=2, three=3)
    b = {'one': 1, 'two': 2, 'three': 3}
    c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
    d = dict([('two', 2), ('one', 1), ('three', 3)])
    e = dict({'three': 3, 'one': 1, 'two': 2})
    f = dict({'one': 1, 'three': 3}, two=2)
    

    All the above examples return a dictionary equal to {"one": 1, "two": 2, "three": 3}.


    現在、我々は我々の話題に来ます.我々は一般的にリストを使用するように簡単ですが、私たちは一般的にリストのリストを使用している場合は何の項目の膨大な数がある場合5000000 . でlists 我々は同じタスクを行う場合は、任意のアイテムをルックアップするには多くの時間がかかるdictionary Pythonでは、Aの平均時間の複雑さのため、かなり高速に行われますdictionary key lookup is O(1) , ハッシュテーブルとして実装されています.の時間複雑性lookup in a list is O(n) 平均して.しかし、使用のもう一つの問題がありますdictionary それは店として多くのスペースを取るkeys and valueslists . それが最高の状況ですspace-time tradeoff .

    If you search for a fixed number of keys, if you grow your haystack size (i.e. the size of the collection you’re searching through) by 10,000x from 1k entries to 10M entries, using a dict is over 5000x faster than using a list! (Source: Fluent Python by Luciano Ramalho)


    でも後にpython 3.6 我々は、新しい実装を持ってdict どちらが少ないmemory 今まで前に、今ではないspace-time tradeoff .

    The dict type has been reimplemented to use a more compact representation based on a proposal by Raymond Hettinger and similar to the PyPy dict implementation. This resulted in dictionaries using 20% to 25% less memory when compared to Python 3.5. (Source : python.org)


    読書ありがとう.