辞書やコレクションPythonのパフォーマンスの違いを理解します

この記事オタク時間Pythonのコア技術と実践的な研究ノート欄

辞書

Python3.7 +において、辞書は秩序であると判定された(注:3.6で、辞書は規則的実装の詳細であり、それは3.7言語機能になり、従って100%3.6の秩序を確保することができない)、および3.6無秩序前に、その可変長サイズ、要素を切断し、任意に変更することができます。

比較するとリストやタプル、辞書より優れた性能は、一定の時間複雑かもしれ(1)O検索、追加、削除操作を完了しました。

一般的な方法を作成します。

>>> d1 = {'name': 'Json', 'age': 20, 'gender': 'male'}
>>> d2 = dict( {'name': 'Json', 'age': 20, 'gender': 'male'})
>>> d3 = dict([('name', 'Json'),('age', 20),('gender','male')])
>>> d4 = dict(name='Json', age=20, gender='male')
>>> d1 == d2 == d3 == d4
True

指数

使用するdict[key]形式インデックスを、そうでない場合、スローされますKeyError例外を。

>>> d1['name']
'Json'
>>> d1['location']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'location'

使用get(key, default)方法は、結合が存在しない場合は、ほかに、例外をスローしないであろうことが返されるデフォルト値を指定します

>>> d1.get('name')
'Json'
>>> d1.get('location')

>>> d1.get('location', None)
None

要素はキーの辞書であるかどうかを確認します。

>>> 'name' in d1        # 同d1.keys()等价
True
>>> 'name' in d1.keys()     
True
>>> 'Json' in d1        
False
>>> 'Json' in d1.values()
True

加えます

>>> d = {'name': 'jason', 'age': 20}
>>> d['gender'] = 'male'
>>> d
{'name': 'jason', 'age': 20, 'gender': 'male'}

[削除]

>>> d.pop('gender')
'male'
>>> d
{'name': 'jason', 'age': 20}

シーケンス

ソートキーによると、

>>> d = {'b': 1, 'v': 20, 'a': 17}
>>> d_sorted_by_key = sorted(d.items(), key=lambda x: x[0])
>>> d_sorted_by_key
[('a', 17), ('b', 1), ('v', 20)]
>>> d
{'b': 1, 'v': 20, 'a': 17}

ソート値に従って

>>> d_sorted_by_value = sorted(d.items(), key = lambda x: x[1])
>>> d_sorted_by_value
[('b', 1), ('a', 17), ('v', 20)]

パフォーマンス分析

例:製品ID、価格:千万製品、などの製品情報があります。今需要がある:プロダクトIDの一部を考えると、価格を見つけます:

1.保存されたデータ一覧

ストレージ構成は以下のように:

products = [
    (143121312, 100), 
    (432314553, 30),
    (32421912367, 150) 
]

そして、時間の複雑さを見つけるために、リスト全体を横断する必要があることであるO(N) でも、最初の並べ替えリスト、その後、バイナリ検索が必要になりますO(LOGN)ソートに時間と必要性の複雑さをO(nlogn)時間。

2.データを保存するために辞書

ストレージ構成は以下のように:

products = {
    '143121312': 100,
    '432314553': 30,
    '32421912367': 150
}

辞書の内部構造は、ハッシュテーブルであるため、それがで可能であるO(1)完全な検索時間の複雑さ。

3.効率の比較

import time
import numpy
def find_product_price_list(products, product_id):
    for id, price in products:
        if id == product_id:
            return price
    return None
def find_product_price_dict(products, product_id):
    for id in products.keys():
        if id == product_id:
            return products_dict[id]
    return None
r = numpy.random.randint(0,10000000,10000000)       # 生成10000000个随机数
id = [str(x) for x in r]
price = [x for x in range(20000000, 30000000)]

products_list = list(zip(id, price))
products_dict = dict(zip(id, price))
# 添加新元素
products_list.append(('111111111', 300))    # 追加到列表末尾
products_dict['111111111'] = 300

start_using_dict = time.perf_counter()
find_product_price_dict(products_dict, '111111111')
end_using_dict = time.perf_counter()
print('time elapse using dict: {}'.format(end_using_dict - start_using_dict))

start_using_list = time.perf_counter()
find_product_price_list(products_dict, '111111111')
end_using_list = time.perf_counter()

print('time elapse using list: {}'.format(end_using_list - start_using_list))

# ===========运行结果============
time elapse using dict: 0.1983588489999999
time elapse using list: 0.41368435999999953

セット

実質的に同一の辞書とセットは、唯一の違いは、要素のランダムな、ユニークな組み合わせの一連のない組一対のキーと値がないことです。

一般的な方法を作成します。

>>> s1 = {1,2,3}
>>> s2 = set([1,2,3])
>>> s1 == s2
True

指数

それはハッシュテーブルであるため、コレクションは、インデックス運用をサポートしていない、とリストは、コレクションの性質上と同じではありません

次のように進み、PythonがスローされますTypeError例外を。

>>> s1[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'set' object is not subscriptable

我々は唯一の要素がコレクション内にあるかどうかを判断することができます。

>>> 1 in s1
True
>>> 10 in s1
False

加えます

>>> s = {1,2,3}
>>> s.add(4)
>>> s
{1, 2, 3, 4}

[削除]

>>> s.remove(4)
>>> s
{1, 2, 3}

注:セットは順不同であり、そうので判断できないpop()要素を除去する方法ので、使用注意を。一般的な削除の採用がremove()可能。

シーケンス

>>> s  = {2,4,546,34}
>>> sorted(s)
[2, 4, 34, 546]

Set操作

共通セットの操作

文法 オペレーティング 説明
セット(リスト1)| セット(LIST2) 連合 List1をし、すべてのデータを含むlist2の新しいコレクション
セット(リスト1)&セット(LIST2) 交差点 新しいコレクションは、リスト1とリスト2の共通要素が含まれています
セット(リスト1) - セット(LIST2) しかしコレクションに表示されlist2の要素にリスト1に表示されません

パフォーマンス分析

あるいは、上記の例では、例えば、今の価格の何種類を計算するのに必要とされます。時間を節約するために、我々は、千万の製品の数が減少しています。

効率を探します

1.データのリストが保存され

2つのサイクルを必要とします。だから、最悪の場合には、当社は必要とはO(n ^ 2)時間の複雑さを。

2.ストアのデータセット

収集以降のみO(1)、その後、唯一の全体的な時間計算要素は繰り返すことができない高度に最適化されたハッシュテーブル、および操作ルックの追加複雑さO(N)

3.効率の比較

import time
import numpy

def find_unique_price_set(products):
    unique_price_set = set()
    for _, price in products:
        unique_price_set.add(price)
    return len(unique_price_set)

def find_unique_price_list(products):
    unique_price_list = []
    for _, price in products: # A
        if price not in unique_price_list: #B
            unique_price_list.append(price)
    return len(unique_price_list)


r = numpy.random.randint(0,1000000,100000)       # 生成100000个随机数
id = [str(x) for x in r]
price = [x for x in range(200000, 300000)]

products = list(zip(id, price))


start_using_set = time.perf_counter()
find_unique_price_set(products)
end_using_set = time.perf_counter()
print('time elapse using set: {}'.format(end_using_set - start_using_set))

start_using_list = time.perf_counter()
find_unique_price_list(products)
end_using_list = time.perf_counter()
print('time elapse using list: {}'.format(end_using_list - start_using_list))

# ===========运行结果============
time elapse using set: 0.00985934799999999
time elapse using list: 65.528253501

、のみ10万データを見ることができるように、ギャップが非常に明白となっています。

交差点、労働組合、差分計算

例えば次交差点、:

import time

list_a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 13, 34, 53, 42, 44]
list_b = [2, 4, 6, 9, 23]

intersection = []

# 列表做交集
start_using_list = time.perf_counter()
for a in list_a:
    for b in list_b:
        if a == b:
            intersection.append(a)
end_using_list = time.perf_counter()

print(intersection)
print('time: {}'.format(end_using_list - start_using_list))

# 集合做交集
start_using_list = time.perf_counter()
intersection = list(set(list_a) & set(list_b))
end_using_list = time.perf_counter()

print(intersection)
print('time: {}'.format(end_using_list - start_using_list))

# ===========运行结果============
[2, 4, 6, 9]
time: 9.622000000000797e-06
[9, 2, 4, 6]
time: 4.169000000001782e-06

おすすめ

転載: www.cnblogs.com/ghostlee/p/12114680.html