Struktur data dan implementasi algoritma dalam python

Struktur data adalah konstruksi dasar di mana Anda membangun program Anda. Setiap struktur data menyediakan cara tertentu untuk mengatur data sehingga dapat diakses secara efisien, bergantung pada kasus penggunaan Anda. Python dikirimkan dengan kumpulan struktur data yang ekstensif di perpustakaan standarnya

Show

Namun, konvensi penamaan Python tidak memberikan tingkat kejelasan yang sama seperti yang Anda temukan di bahasa lain. Di Jawa, daftar bukan hanya

>>> from collections import ChainMap
>>> dict1 = {"one": 1, "two": 2}
>>> dict2 = {"three": 3, "four": 4}
>>> chain = ChainMap(dict1, dict2)

>>> chain
ChainMap({'one': 1, 'two': 2}, {'three': 3, 'four': 4})

>>> # ChainMap searches each collection in the chain
>>> # from left to right until it finds the key (or fails):
>>> chain["three"]
3
>>> chain["one"]
1
>>> chain["missing"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'missing'
6—melainkan
>>> from collections import ChainMap
>>> dict1 = {"one": 1, "two": 2}
>>> dict2 = {"three": 3, "four": 4}
>>> chain = ChainMap(dict1, dict2)

>>> chain
ChainMap({'one': 1, 'two': 2}, {'three': 3, 'four': 4})

>>> # ChainMap searches each collection in the chain
>>> # from left to right until it finds the key (or fails):
>>> chain["three"]
3
>>> chain["one"]
1
>>> chain["missing"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'missing'
7 atau
>>> from collections import ChainMap
>>> dict1 = {"one": 1, "two": 2}
>>> dict2 = {"three": 3, "four": 4}
>>> chain = ChainMap(dict1, dict2)

>>> chain
ChainMap({'one': 1, 'two': 2}, {'three': 3, 'four': 4})

>>> # ChainMap searches each collection in the chain
>>> # from left to right until it finds the key (or fails):
>>> chain["three"]
3
>>> chain["one"]
1
>>> chain["missing"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'missing'
8. Tidak demikian halnya dengan Python. Bahkan pengembang Python berpengalaman terkadang bertanya-tanya apakah tipe
>>> from collections import ChainMap
>>> dict1 = {"one": 1, "two": 2}
>>> dict2 = {"three": 3, "four": 4}
>>> chain = ChainMap(dict1, dict2)

>>> chain
ChainMap({'one': 1, 'two': 2}, {'three': 3, 'four': 4})

>>> # ChainMap searches each collection in the chain
>>> # from left to right until it finds the key (or fails):
>>> chain["three"]
3
>>> chain["one"]
1
>>> chain["missing"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'missing'
6 bawaan diimplementasikan sebagai daftar tertaut atau larik dinamis

Dalam tutorial ini, Anda akan belajar

  • Tipe data abstrak umum mana yang dibangun ke dalam pustaka standar Python
  • Bagaimana tipe data abstrak yang paling umum dipetakan ke skema penamaan Python
  • Cara menempatkan tipe data abstrak untuk penggunaan praktis dalam berbagai algoritme

Catatan. Tutorial ini diadaptasi dari bab “Common Data Structures in Python” di Python Tricks. Buku. Jika Anda menikmati apa yang Anda baca di bawah ini, maka pastikan untuk memeriksa sisa buku ini

Download Gratis. Dapatkan contoh bab dari Trik Python. Buku yang menunjukkan kepada Anda praktik terbaik Python dengan contoh sederhana yang dapat Anda terapkan secara instan untuk menulis kode + Pythonic yang lebih indah

Kamus, Peta, dan Tabel Hash

Dalam Python, kamus (atau singkatnya dikte) adalah struktur data pusat. Dicts menyimpan sejumlah objek yang berubah-ubah, masing-masing diidentifikasi dengan kunci kamus yang unik

Kamus juga sering disebut peta, peta hash, tabel pencarian, atau array asosiatif. Mereka memungkinkan pencarian, penyisipan, dan penghapusan objek apa pun yang terkait dengan kunci yang diberikan secara efisien

Buku telepon membuat analog dunia nyata yang layak untuk objek kamus. Mereka memungkinkan Anda dengan cepat mengambil informasi (nomor telepon) yang terkait dengan kunci yang diberikan (nama seseorang). Alih-alih harus membaca buku telepon dari depan ke belakang untuk menemukan nomor seseorang, Anda dapat melompat kurang lebih langsung ke nama dan mencari informasi terkait

Analogi ini agak rusak dalam hal bagaimana informasi diatur untuk memungkinkan pencarian cepat. Tetapi karakteristik kinerja fundamental tetap berlaku. Kamus memungkinkan Anda menemukan informasi yang terkait dengan kunci tertentu dengan cepat

Kamus adalah salah satu struktur data yang paling penting dan sering digunakan dalam ilmu komputer. Jadi, bagaimana cara Python menangani kamus?

Hilangkan iklan

>>> from types import MappingProxyType >>> writable = {"one": 1, "two": 2} >>> read_only = MappingProxyType(writable) >>> # The proxy is read-only: >>> read_only["one"] 1 >>> read_only["one"] = 23 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'mappingproxy' object does not support item assignment >>> # Updates to the original are reflected in the proxy: >>> writable["one"] = 42 >>> read_only mappingproxy({'one': 42, 'two': 2}) _0. Kamus Masuk Anda

Karena kamus sangat penting, Python menampilkan implementasi kamus yang kuat yang dibangun langsung ke dalam bahasa inti. tipe data

Python juga menyediakan beberapa gula sintaksis yang berguna untuk bekerja dengan kamus di program Anda. Misalnya, sintaks ekspresi kamus kurung kurawal ({ }) dan memungkinkan Anda untuk dengan mudah menentukan objek kamus baru

>>>

>>> phonebook = {
..     "bob": 7387,
..     "alice": 3719,
..     "jack": 7052,
.. }

>>> squares = {x: x * x for x in range(6)}

>>> phonebook["alice"]
3719

>>> squares
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
_

Ada beberapa batasan pada objek mana yang dapat digunakan sebagai kunci yang valid

Kamus Python diindeks oleh kunci yang bisa dari jenis apa pun. Objek hashable memiliki nilai hash yang tidak pernah berubah selama hidupnya (lihat

>>> from types import MappingProxyType
>>> writable = {"one": 1, "two": 2}
>>> read_only = MappingProxyType(writable)

>>> # The proxy is read-only:
>>> read_only["one"]
1
>>> read_only["one"] = 23
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'mappingproxy' object does not support item assignment

>>> # Updates to the original are reflected in the proxy:
>>> writable["one"] = 42
>>> read_only
mappingproxy({'one': 42, 'two': 2})
2), dan dapat dibandingkan dengan objek lain (lihat
>>> from types import MappingProxyType
>>> writable = {"one": 1, "two": 2}
>>> read_only = MappingProxyType(writable)

>>> # The proxy is read-only:
>>> read_only["one"]
1
>>> read_only["one"] = 23
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'mappingproxy' object does not support item assignment

>>> # Updates to the original are reflected in the proxy:
>>> writable["one"] = 42
>>> read_only
mappingproxy({'one': 42, 'two': 2})
3). Objek hashable yang membandingkan sama harus memiliki nilai hash yang sama

Jenis yang tidak dapat diubah seperti string dan angka dapat di-hash dan berfungsi dengan baik sebagai kunci kamus. Anda juga dapat menggunakan sebagai kunci kamus asalkan hanya berisi tipe hashable itu sendiri

Untuk sebagian besar kasus penggunaan, implementasi kamus bawaan Python akan melakukan semua yang Anda butuhkan. Kamus sangat dioptimalkan dan mendasari banyak bagian bahasa. Misalnya, dan variabel dalam keduanya disimpan secara internal dalam kamus

Kamus Python didasarkan pada implementasi tabel hash yang teruji dengan baik dan disetel dengan baik yang memberikan karakteristik kinerja yang Anda harapkan. O(1) kompleksitas waktu untuk operasi pencarian, penyisipan, pembaruan, dan penghapusan dalam kasus rata-rata

Ada sedikit alasan untuk tidak menggunakan implementasi standar

>>> from types import MappingProxyType
>>> writable = {"one": 1, "two": 2}
>>> read_only = MappingProxyType(writable)

>>> # The proxy is read-only:
>>> read_only["one"]
1
>>> read_only["one"] = 23
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'mappingproxy' object does not support item assignment

>>> # Updates to the original are reflected in the proxy:
>>> writable["one"] = 42
>>> read_only
mappingproxy({'one': 42, 'two': 2})
_0 yang disertakan dengan Python. Namun, ada implementasi kamus pihak ketiga khusus, seperti daftar lewati atau kamus berbasis B-tree

Selain objek

>>> from types import MappingProxyType
>>> writable = {"one": 1, "two": 2}
>>> read_only = MappingProxyType(writable)

>>> # The proxy is read-only:
>>> read_only["one"]
1
>>> read_only["one"] = 23
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'mappingproxy' object does not support item assignment

>>> # Updates to the original are reflected in the proxy:
>>> writable["one"] = 42
>>> read_only
mappingproxy({'one': 42, 'two': 2})
_0 biasa, pustaka standar Python juga menyertakan sejumlah implementasi kamus khusus. Kamus khusus ini semuanya didasarkan pada kelas kamus bawaan (dan berbagi karakteristik kinerjanya), tetapi juga menyertakan beberapa fitur kenyamanan tambahan

Mari kita lihat mereka

>>> from types import MappingProxyType >>> writable = {"one": 1, "two": 2} >>> read_only = MappingProxyType(writable) >>> # The proxy is read-only: >>> read_only["one"] 1 >>> read_only["one"] = 23 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'mappingproxy' object does not support item assignment >>> # Updates to the original are reflected in the proxy: >>> writable["one"] = 42 >>> read_only mappingproxy({'one': 42, 'two': 2}) _7. Ingat Urutan Penyisipan Kunci

Python menyertakan subkelas

>>> from types import MappingProxyType
>>> writable = {"one": 1, "two": 2}
>>> read_only = MappingProxyType(writable)

>>> # The proxy is read-only:
>>> read_only["one"]
1
>>> read_only["one"] = 23
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'mappingproxy' object does not support item assignment

>>> # Updates to the original are reflected in the proxy:
>>> writable["one"] = 42
>>> read_only
mappingproxy({'one': 42, 'two': 2})
0 khusus yang mengingat urutan penyisipan kunci yang ditambahkan ke dalamnya.
>>> from types import MappingProxyType
>>> writable = {"one": 1, "two": 2}
>>> read_only = MappingProxyType(writable)

>>> # The proxy is read-only:
>>> read_only["one"]
1
>>> read_only["one"] = 23
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'mappingproxy' object does not support item assignment

>>> # Updates to the original are reflected in the proxy:
>>> writable["one"] = 42
>>> read_only
mappingproxy({'one': 42, 'two': 2})
_7

Catatan.

>>> arr = ["one", "two", "three"]
>>> arr[0]
'one'

>>> # Lists have a nice repr:
>>> arr
['one', 'two', 'three']

>>> # Lists are mutable:
>>> arr[1] = "hello"
>>> arr
['one', 'hello', 'three']

>>> del arr[1]
>>> arr
['one', 'three']

>>> # Lists can hold arbitrary data types:
>>> arr.append(23)
>>> arr
['one', 'three', 23]
0 bukan bagian bawaan dari bahasa inti dan harus diimpor dari modul
>>> arr = ["one", "two", "three"]
>>> arr[0]
'one'

>>> # Lists have a nice repr:
>>> arr
['one', 'two', 'three']

>>> # Lists are mutable:
>>> arr[1] = "hello"
>>> arr
['one', 'hello', 'three']

>>> del arr[1]
>>> arr
['one', 'three']

>>> # Lists can hold arbitrary data types:
>>> arr.append(23)
>>> arr
['one', 'three', 23]
1 di perpustakaan standar

Sementara standar

>>> from types import MappingProxyType
>>> writable = {"one": 1, "two": 2}
>>> read_only = MappingProxyType(writable)

>>> # The proxy is read-only:
>>> read_only["one"]
1
>>> read_only["one"] = 23
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'mappingproxy' object does not support item assignment

>>> # Updates to the original are reflected in the proxy:
>>> writable["one"] = 42
>>> read_only
mappingproxy({'one': 42, 'two': 2})
0 instance mempertahankan urutan penyisipan kunci di Python 3. 6 ke atas, ini hanyalah efek samping dari implementasi CPython dan tidak ditentukan dalam spesifikasi bahasa hingga Python 3. 7. Jadi, jika urutan kunci penting agar algoritme Anda berfungsi, sebaiknya komunikasikan ini secara jelas dengan menggunakan kelas
>>> arr = ["one", "two", "three"]
>>> arr[0]
'one'

>>> # Lists have a nice repr:
>>> arr
['one', 'two', 'three']

>>> # Lists are mutable:
>>> arr[1] = "hello"
>>> arr
['one', 'hello', 'three']

>>> del arr[1]
>>> arr
['one', 'three']

>>> # Lists can hold arbitrary data types:
>>> arr.append(23)
>>> arr
['one', 'three', 23]
0 secara eksplisit

>>>

>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
_

Sampai Python 3. 8, Anda tidak dapat mengulangi item kamus dalam urutan terbalik menggunakan

>>> arr = ["one", "two", "three"]
>>> arr[0]
'one'

>>> # Lists have a nice repr:
>>> arr
['one', 'two', 'three']

>>> # Lists are mutable:
>>> arr[1] = "hello"
>>> arr
['one', 'hello', 'three']

>>> del arr[1]
>>> arr
['one', 'three']

>>> # Lists can hold arbitrary data types:
>>> arr.append(23)
>>> arr
['one', 'three', 23]
4. Hanya
>>> arr = ["one", "two", "three"]
>>> arr[0]
'one'

>>> # Lists have a nice repr:
>>> arr
['one', 'two', 'three']

>>> # Lists are mutable:
>>> arr[1] = "hello"
>>> arr
['one', 'hello', 'three']

>>> del arr[1]
>>> arr
['one', 'three']

>>> # Lists can hold arbitrary data types:
>>> arr.append(23)
>>> arr
['one', 'three', 23]
_0 instans yang menawarkan fungsionalitas tersebut. Bahkan di Python 3. 8,
>>> from types import MappingProxyType
>>> writable = {"one": 1, "two": 2}
>>> read_only = MappingProxyType(writable)

>>> # The proxy is read-only:
>>> read_only["one"]
1
>>> read_only["one"] = 23
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'mappingproxy' object does not support item assignment

>>> # Updates to the original are reflected in the proxy:
>>> writable["one"] = 42
>>> read_only
mappingproxy({'one': 42, 'two': 2})
0 dan
>>> arr = ["one", "two", "three"]
>>> arr[0]
'one'

>>> # Lists have a nice repr:
>>> arr
['one', 'two', 'three']

>>> # Lists are mutable:
>>> arr[1] = "hello"
>>> arr
['one', 'hello', 'three']

>>> del arr[1]
>>> arr
['one', 'three']

>>> # Lists can hold arbitrary data types:
>>> arr.append(23)
>>> arr
['one', 'three', 23]
0 objek tidak persis sama.
>>> arr = ["one", "two", "three"]
>>> arr[0]
'one'

>>> # Lists have a nice repr:
>>> arr
['one', 'two', 'three']

>>> # Lists are mutable:
>>> arr[1] = "hello"
>>> arr
['one', 'hello', 'three']

>>> del arr[1]
>>> arr
['one', 'three']

>>> # Lists can hold arbitrary data types:
>>> arr.append(23)
>>> arr
['one', 'three', 23]
0 instans memiliki metode
>>> arr = ["one", "two", "three"]
>>> arr[0]
'one'

>>> # Lists have a nice repr:
>>> arr
['one', 'two', 'three']

>>> # Lists are mutable:
>>> arr[1] = "hello"
>>> arr
['one', 'hello', 'three']

>>> del arr[1]
>>> arr
['one', 'three']

>>> # Lists can hold arbitrary data types:
>>> arr.append(23)
>>> arr
['one', 'three', 23]
9 yang tidak tersedia pada instans
>>> from types import MappingProxyType
>>> writable = {"one": 1, "two": 2}
>>> read_only = MappingProxyType(writable)

>>> # The proxy is read-only:
>>> read_only["one"]
1
>>> read_only["one"] = 23
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'mappingproxy' object does not support item assignment

>>> # Updates to the original are reflected in the proxy:
>>> writable["one"] = 42
>>> read_only
mappingproxy({'one': 42, 'two': 2})
0 biasa, serta lebih dapat disesuaikan daripada instans
>>> from types import MappingProxyType
>>> writable = {"one": 1, "two": 2}
>>> read_only = MappingProxyType(writable)

>>> # The proxy is read-only:
>>> read_only["one"]
1
>>> read_only["one"] = 23
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'mappingproxy' object does not support item assignment

>>> # Updates to the original are reflected in the proxy:
>>> writable["one"] = 42
>>> read_only
mappingproxy({'one': 42, 'two': 2})
0 biasa

>>> arr = ("one", "two", "three") >>> arr[0] 'one' >>> # Tuples have a nice repr: >>> arr ('one', 'two', 'three') >>> # Tuples are immutable: >>> arr[1] = "hello" Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment >>> del arr[1] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object doesn't support item deletion >>> # Tuples can hold arbitrary data types: >>> # (Adding elements creates a copy of the tuple) >>> arr + (23,) ('one', 'two', 'three', 23) 3. Mengembalikan Nilai Default untuk Kunci yang Hilang

Kelas adalah subkelas kamus lain yang menerima panggilan dalam konstruktornya yang nilai pengembaliannya akan digunakan jika kunci yang diminta tidak dapat ditemukan

Ini dapat menghemat beberapa pengetikan dan membuat niat Anda lebih jelas dibandingkan dengan menggunakan

>>> arr = ("one", "two", "three")
>>> arr[0]
'one'

>>> # Tuples have a nice repr:
>>> arr
('one', 'two', 'three')

>>> # Tuples are immutable:
>>> arr[1] = "hello"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

>>> del arr[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object doesn't support item deletion

>>> # Tuples can hold arbitrary data types:
>>> # (Adding elements creates a copy of the tuple)
>>> arr + (23,)
('one', 'two', 'three', 23)
5 atau menangkap pengecualian
>>> arr = ("one", "two", "three")
>>> arr[0]
'one'

>>> # Tuples have a nice repr:
>>> arr
('one', 'two', 'three')

>>> # Tuples are immutable:
>>> arr[1] = "hello"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

>>> del arr[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object doesn't support item deletion

>>> # Tuples can hold arbitrary data types:
>>> # (Adding elements creates a copy of the tuple)
>>> arr + (23,)
('one', 'two', 'three', 23)
6 dalam kamus biasa

>>>

>>> from collections import defaultdict
>>> dd = defaultdict(list)

>>> # Accessing a missing key creates it and
>>> # initializes it using the default factory,
>>> # i.e. list() in this example:
>>> dd["dogs"].append("Rufus")
>>> dd["dogs"].append("Kathrin")
>>> dd["dogs"].append("Mr Sniffles")

>>> dd["dogs"]
['Rufus', 'Kathrin', 'Mr Sniffles']
_

Hilangkan iklan

>>> arr = ("one", "two", "three") >>> arr[0] 'one' >>> # Tuples have a nice repr: >>> arr ('one', 'two', 'three') >>> # Tuples are immutable: >>> arr[1] = "hello" Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment >>> del arr[1] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object doesn't support item deletion >>> # Tuples can hold arbitrary data types: >>> # (Adding elements creates a copy of the tuple) >>> arr + (23,) ('one', 'two', 'three', 23) 7. Cari Beberapa Kamus sebagai Pemetaan Tunggal

Struktur data mengelompokkan beberapa kamus ke dalam satu pemetaan. Pencarian mencari pemetaan yang mendasarinya satu per satu hingga kunci ditemukan. Penyisipan, pembaruan, dan penghapusan hanya memengaruhi pemetaan pertama yang ditambahkan ke rantai

>>> ________0______

>>> arr = ("one", "two", "three") >>> arr[0] 'one' >>> # Tuples have a nice repr: >>> arr ('one', 'two', 'three') >>> # Tuples are immutable: >>> arr[1] = "hello" Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment >>> del arr[1] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object doesn't support item deletion >>> # Tuples can hold arbitrary data types: >>> # (Adding elements creates a copy of the tuple) >>> arr + (23,) ('one', 'two', 'three', 23) _9. Pembungkus untuk Membuat Kamus Hanya-Baca

adalah pembungkus di sekitar kamus standar yang menyediakan tampilan hanya-baca ke dalam data kamus yang dibungkus. Kelas ini ditambahkan dalam Python 3. 3 dan dapat digunakan untuk membuat kamus versi proksi yang tidak dapat diubah

>>> import array
>>> arr = array.array("f", (1.0, 1.5, 2.0, 2.5))
>>> arr[1]
1.5

>>> # Arrays have a nice repr:
>>> arr
array('f', [1.0, 1.5, 2.0, 2.5])

>>> # Arrays are mutable:
>>> arr[1] = 23.0
>>> arr
array('f', [1.0, 23.0, 2.0, 2.5])

>>> del arr[1]
>>> arr
array('f', [1.0, 2.0, 2.5])

>>> arr.append(42.0)
>>> arr
array('f', [1.0, 2.0, 2.5, 42.0])

>>> # Arrays are "typed":
>>> arr[1] = "hello"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: must be real number, not str
0 dapat membantu jika, misalnya, Anda ingin mengembalikan kamus yang membawa status internal dari kelas atau modul sambil mencegah akses tulis ke objek ini. Menggunakan
>>> import array
>>> arr = array.array("f", (1.0, 1.5, 2.0, 2.5))
>>> arr[1]
1.5

>>> # Arrays have a nice repr:
>>> arr
array('f', [1.0, 1.5, 2.0, 2.5])

>>> # Arrays are mutable:
>>> arr[1] = 23.0
>>> arr
array('f', [1.0, 23.0, 2.0, 2.5])

>>> del arr[1]
>>> arr
array('f', [1.0, 2.0, 2.5])

>>> arr.append(42.0)
>>> arr
array('f', [1.0, 2.0, 2.5, 42.0])

>>> # Arrays are "typed":
>>> arr[1] = "hello"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: must be real number, not str
_0 memungkinkan Anda menerapkan batasan ini tanpa terlebih dahulu harus membuat salinan lengkap kamus

>>>

>>> from types import MappingProxyType
>>> writable = {"one": 1, "two": 2}
>>> read_only = MappingProxyType(writable)

>>> # The proxy is read-only:
>>> read_only["one"]
1
>>> read_only["one"] = 23
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'mappingproxy' object does not support item assignment

>>> # Updates to the original are reflected in the proxy:
>>> writable["one"] = 42
>>> read_only
mappingproxy({'one': 42, 'two': 2})
_

Kamus dengan Python. Ringkasan

Semua implementasi kamus Python yang tercantum dalam tutorial ini adalah implementasi valid yang dibangun ke dalam pustaka standar Python

Jika Anda sedang mencari rekomendasi umum tentang tipe pemetaan mana yang akan digunakan dalam program Anda, saya akan mengarahkan Anda ke tipe data

>>> from types import MappingProxyType
>>> writable = {"one": 1, "two": 2}
>>> read_only = MappingProxyType(writable)

>>> # The proxy is read-only:
>>> read_only["one"]
1
>>> read_only["one"] = 23
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'mappingproxy' object does not support item assignment

>>> # Updates to the original are reflected in the proxy:
>>> writable["one"] = 42
>>> read_only
mappingproxy({'one': 42, 'two': 2})
0 bawaan. Ini adalah penerapan tabel hash yang serbaguna dan dioptimalkan yang dibangun langsung ke dalam bahasa inti

Saya akan merekomendasikan agar Anda menggunakan salah satu jenis data lain yang tercantum di sini hanya jika Anda memiliki persyaratan khusus yang melampaui apa yang disediakan oleh

>>> from types import MappingProxyType
>>> writable = {"one": 1, "two": 2}
>>> read_only = MappingProxyType(writable)

>>> # The proxy is read-only:
>>> read_only["one"]
1
>>> read_only["one"] = 23
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'mappingproxy' object does not support item assignment

>>> # Updates to the original are reflected in the proxy:
>>> writable["one"] = 42
>>> read_only
mappingproxy({'one': 42, 'two': 2})
0

Semua implementasi adalah opsi yang valid, tetapi kode Anda akan lebih jelas dan lebih mudah dipelihara jika sebagian besar bergantung pada kamus Python standar

Struktur Data Array

Array adalah struktur data fundamental yang tersedia di sebagian besar bahasa pemrograman, dan memiliki banyak kegunaan di berbagai algoritma

Di bagian ini, Anda akan melihat implementasi larik di Python yang hanya menggunakan fitur atau fungsionalitas bahasa inti yang disertakan dalam pustaka standar Python. Anda akan melihat kekuatan dan kelemahan dari setiap pendekatan sehingga Anda dapat memutuskan penerapan mana yang tepat untuk kasus penggunaan Anda

Tapi sebelum kita masuk, mari kita bahas beberapa dasar terlebih dahulu. Bagaimana cara kerja array, dan untuk apa mereka digunakan?

Struktur data dan implementasi algoritma dalam python

Karena array menyimpan informasi dalam blok memori yang bersebelahan, mereka dianggap sebagai struktur data yang bersebelahan (berlawanan dengan struktur data tertaut seperti daftar tertaut, misalnya)

Analogi dunia nyata untuk struktur data array adalah tempat parkir. Anda dapat melihat tempat parkir secara keseluruhan dan memperlakukannya sebagai satu objek, tetapi di dalam tempat parkir terdapat tempat parkir yang diindeks dengan nomor unik. Tempat parkir adalah wadah untuk kendaraan — setiap tempat parkir bisa kosong atau ada mobil, sepeda motor, atau kendaraan lain yang diparkir di atasnya

Tapi tidak semua tempat parkir sama. Beberapa tempat parkir mungkin dibatasi hanya untuk satu jenis kendaraan. Misalnya, tempat parkir rumah motor tidak mengizinkan sepeda diparkir di atasnya. Tempat parkir terbatas sesuai dengan struktur data array yang diketik yang memungkinkan hanya elemen yang memiliki tipe data yang sama disimpan di dalamnya

Dari segi kinerja, sangat cepat untuk mencari elemen yang terkandung dalam larik yang diberi indeks elemen. Implementasi array yang tepat menjamin waktu akses O(1) yang konstan untuk kasus ini

Python menyertakan beberapa struktur data mirip-array di perpustakaan standarnya yang masing-masing memiliki karakteristik yang sedikit berbeda. Mari lihat

Hilangkan iklan

>>> from collections import ChainMap >>> dict1 = {"one": 1, "two": 2} >>> dict2 = {"three": 3, "four": 4} >>> chain = ChainMap(dict1, dict2) >>> chain ChainMap({'one': 1, 'two': 2}, {'three': 3, 'four': 4}) >>> # ChainMap searches each collection in the chain >>> # from left to right until it finds the key (or fails): >>> chain["three"] 3 >>> chain["one"] 1 >>> chain["missing"] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'missing' _6. Array Dinamis yang Dapat Diubah

adalah bagian dari inti bahasa Python. Terlepas dari namanya, daftar Python diimplementasikan sebagai array dinamis di belakang layar

Ini berarti daftar memungkinkan elemen ditambahkan atau dihapus, dan daftar akan secara otomatis menyesuaikan backing store yang menyimpan elemen-elemen ini dengan mengalokasikan atau melepaskan memori.

Daftar Python dapat menampung elemen arbitrer — semuanya adalah objek dalam Python, termasuk fungsi. Oleh karena itu, Anda dapat mencampur dan mencocokkan berbagai jenis tipe data dan menyimpan semuanya dalam satu daftar

Ini bisa menjadi fitur yang hebat, tetapi sisi negatifnya adalah mendukung banyak tipe data pada saat yang sama berarti bahwa data umumnya kurang padat. Akibatnya, seluruh struktur memakan lebih banyak ruang

>>>

>>> arr = ["one", "two", "three"]
>>> arr[0]
'one'

>>> # Lists have a nice repr:
>>> arr
['one', 'two', 'three']

>>> # Lists are mutable:
>>> arr[1] = "hello"
>>> arr
['one', 'hello', 'three']

>>> del arr[1]
>>> arr
['one', 'three']

>>> # Lists can hold arbitrary data types:
>>> arr.append(23)
>>> arr
['one', 'three', 23]
_

>>> from types import MappingProxyType >>> writable = {"one": 1, "two": 2} >>> read_only = MappingProxyType(writable) >>> # The proxy is read-only: >>> read_only["one"] 1 >>> read_only["one"] = 23 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'mappingproxy' object does not support item assignment >>> # Updates to the original are reflected in the proxy: >>> writable["one"] = 42 >>> read_only mappingproxy({'one': 42, 'two': 2}) _4. Kontainer yang tidak dapat diubah

Sama seperti daftar, merupakan bagian dari bahasa inti Python. Tidak seperti daftar, objek

>>> from types import MappingProxyType
>>> writable = {"one": 1, "two": 2}
>>> read_only = MappingProxyType(writable)

>>> # The proxy is read-only:
>>> read_only["one"]
1
>>> read_only["one"] = 23
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'mappingproxy' object does not support item assignment

>>> # Updates to the original are reflected in the proxy:
>>> writable["one"] = 42
>>> read_only
mappingproxy({'one': 42, 'two': 2})
4 Python tidak dapat diubah. Ini berarti elemen tidak dapat ditambahkan atau dihapus secara dinamis—semua elemen dalam tuple harus ditentukan pada waktu pembuatan

Tuple adalah struktur data lain yang dapat menampung elemen tipe data arbitrer. Memiliki fleksibilitas ini sangat kuat, tetapi sekali lagi, ini juga berarti bahwa data tidak terlalu padat dibandingkan dengan array yang diketik

>>>

>>> arr = ("one", "two", "three")
>>> arr[0]
'one'

>>> # Tuples have a nice repr:
>>> arr
('one', 'two', 'three')

>>> # Tuples are immutable:
>>> arr[1] = "hello"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

>>> del arr[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object doesn't support item deletion

>>> # Tuples can hold arbitrary data types:
>>> # (Adding elements creates a copy of the tuple)
>>> arr + (23,)
('one', 'two', 'three', 23)
_

>>> import array >>> arr = array.array("f", (1.0, 1.5, 2.0, 2.5)) >>> arr[1] 1.5 >>> # Arrays have a nice repr: >>> arr array('f', [1.0, 1.5, 2.0, 2.5]) >>> # Arrays are mutable: >>> arr[1] = 23.0 >>> arr array('f', [1.0, 23.0, 2.0, 2.5]) >>> del arr[1] >>> arr array('f', [1.0, 2.0, 2.5]) >>> arr.append(42.0) >>> arr array('f', [1.0, 2.0, 2.5, 42.0]) >>> # Arrays are "typed": >>> arr[1] = "hello" Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: must be real number, not str _8. Array Berketik Dasar

Modul

>>> import array
>>> arr = array.array("f", (1.0, 1.5, 2.0, 2.5))
>>> arr[1]
1.5

>>> # Arrays have a nice repr:
>>> arr
array('f', [1.0, 1.5, 2.0, 2.5])

>>> # Arrays are mutable:
>>> arr[1] = 23.0
>>> arr
array('f', [1.0, 23.0, 2.0, 2.5])

>>> del arr[1]
>>> arr
array('f', [1.0, 2.0, 2.5])

>>> arr.append(42.0)
>>> arr
array('f', [1.0, 2.0, 2.5, 42.0])

>>> # Arrays are "typed":
>>> arr[1] = "hello"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: must be real number, not str
9 Python menyediakan penyimpanan hemat ruang untuk tipe data dasar gaya-C seperti byte, bilangan bulat 32-bit, angka floating-point, dan sebagainya

Array yang dibuat dengan kelas

>>> import array
>>> arr = array.array("f", (1.0, 1.5, 2.0, 2.5))
>>> arr[1]
1.5

>>> # Arrays have a nice repr:
>>> arr
array('f', [1.0, 1.5, 2.0, 2.5])

>>> # Arrays are mutable:
>>> arr[1] = 23.0
>>> arr
array('f', [1.0, 23.0, 2.0, 2.5])

>>> del arr[1]
>>> arr
array('f', [1.0, 2.0, 2.5])

>>> arr.append(42.0)
>>> arr
array('f', [1.0, 2.0, 2.5, 42.0])

>>> # Arrays are "typed":
>>> arr[1] = "hello"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: must be real number, not str
_8 dapat berubah dan berperilaku mirip dengan daftar kecuali satu perbedaan penting. mereka diketik array yang dibatasi untuk satu tipe data

Karena kendala ini,

>>> import array
>>> arr = array.array("f", (1.0, 1.5, 2.0, 2.5))
>>> arr[1]
1.5

>>> # Arrays have a nice repr:
>>> arr
array('f', [1.0, 1.5, 2.0, 2.5])

>>> # Arrays are mutable:
>>> arr[1] = 23.0
>>> arr
array('f', [1.0, 23.0, 2.0, 2.5])

>>> del arr[1]
>>> arr
array('f', [1.0, 2.0, 2.5])

>>> arr.append(42.0)
>>> arr
array('f', [1.0, 2.0, 2.5, 42.0])

>>> # Arrays are "typed":
>>> arr[1] = "hello"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: must be real number, not str
_8 objek dengan banyak elemen lebih hemat ruang daripada daftar dan tupel. Elemen yang disimpan di dalamnya dikemas rapat, dan ini berguna jika Anda perlu menyimpan banyak elemen dengan jenis yang sama

Selain itu, array mendukung banyak metode yang sama seperti daftar reguler, dan Anda mungkin dapat menggunakannya sebagai pengganti drop-in tanpa memerlukan perubahan lain pada kode aplikasi Anda

>>>

>>> import array
>>> arr = array.array("f", (1.0, 1.5, 2.0, 2.5))
>>> arr[1]
1.5

>>> # Arrays have a nice repr:
>>> arr
array('f', [1.0, 1.5, 2.0, 2.5])

>>> # Arrays are mutable:
>>> arr[1] = 23.0
>>> arr
array('f', [1.0, 23.0, 2.0, 2.5])

>>> del arr[1]
>>> arr
array('f', [1.0, 2.0, 2.5])

>>> arr.append(42.0)
>>> arr
array('f', [1.0, 2.0, 2.5, 42.0])

>>> # Arrays are "typed":
>>> arr[1] = "hello"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: must be real number, not str
_

>>> arr = "abcd" >>> arr[1] 'b' >>> arr 'abcd' >>> # Strings are immutable: >>> arr[1] = "e" Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'str' object does not support item assignment >>> del arr[1] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'str' object doesn't support item deletion >>> # Strings can be unpacked into a list to >>> # get a mutable representation: >>> list("abcd") ['a', 'b', 'c', 'd'] >>> "".join(list("abcd")) 'abcd' >>> # Strings are recursive data structures: >>> type("abc") "<class 'str'>" >>> type("abc"[0]) "<class 'str'>" _2. Array Karakter Unicode yang Tidak Dapat Diubah

Piton 3. x menggunakan objek untuk menyimpan data tekstual sebagai rangkaian karakter Unicode yang tidak dapat diubah. Secara praktis, itu berarti

>>> arr = "abcd"
>>> arr[1]
'b'

>>> arr
'abcd'

>>> # Strings are immutable:
>>> arr[1] = "e"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

>>> del arr[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object doesn't support item deletion

>>> # Strings can be unpacked into a list to
>>> # get a mutable representation:
>>> list("abcd")
['a', 'b', 'c', 'd']
>>> "".join(list("abcd"))
'abcd'

>>> # Strings are recursive data structures:
>>> type("abc")
"<class 'str'>"
>>> type("abc"[0])
"<class 'str'>"
2 adalah susunan karakter yang tidak dapat diubah. Anehnya, ini juga merupakan struktur data rekursif—setiap karakter dalam string itu sendiri adalah objek
>>> arr = "abcd"
>>> arr[1]
'b'

>>> arr
'abcd'

>>> # Strings are immutable:
>>> arr[1] = "e"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

>>> del arr[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object doesn't support item deletion

>>> # Strings can be unpacked into a list to
>>> # get a mutable representation:
>>> list("abcd")
['a', 'b', 'c', 'd']
>>> "".join(list("abcd"))
'abcd'

>>> # Strings are recursive data structures:
>>> type("abc")
"<class 'str'>"
>>> type("abc"[0])
"<class 'str'>"
2 dengan panjang 1

Objek string hemat ruang karena dikemas dengan rapat dan berspesialisasi dalam satu tipe data. Jika Anda menyimpan teks Unicode, maka Anda harus menggunakan string

Karena string tidak dapat diubah dalam Python, memodifikasi string memerlukan pembuatan salinan yang dimodifikasi. Setara terdekat dengan string yang bisa berubah adalah menyimpan karakter individual di dalam daftar

>>>

>>> arr = "abcd"
>>> arr[1]
'b'

>>> arr
'abcd'

>>> # Strings are immutable:
>>> arr[1] = "e"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

>>> del arr[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object doesn't support item deletion

>>> # Strings can be unpacked into a list to
>>> # get a mutable representation:
>>> list("abcd")
['a', 'b', 'c', 'd']
>>> "".join(list("abcd"))
'abcd'

>>> # Strings are recursive data structures:
>>> type("abc")
"<class 'str'>"
>>> type("abc"[0])
"<class 'str'>"
_

Hilangkan iklan

>>> arr = "abcd" >>> arr[1] 'b' >>> arr 'abcd' >>> # Strings are immutable: >>> arr[1] = "e" Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'str' object does not support item assignment >>> del arr[1] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'str' object doesn't support item deletion >>> # Strings can be unpacked into a list to >>> # get a mutable representation: >>> list("abcd") ['a', 'b', 'c', 'd'] >>> "".join(list("abcd")) 'abcd' >>> # Strings are recursive data structures: >>> type("abc") "<class 'str'>" >>> type("abc"[0]) "<class 'str'>" _6. Array Byte Tunggal yang Tidak Dapat Diubah

objek adalah urutan byte tunggal yang tidak dapat diubah, atau bilangan bulat dalam rentang 0 ≤ x ≤ 255. Secara konseptual, objek

>>> arr = "abcd"
>>> arr[1]
'b'

>>> arr
'abcd'

>>> # Strings are immutable:
>>> arr[1] = "e"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

>>> del arr[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object doesn't support item deletion

>>> # Strings can be unpacked into a list to
>>> # get a mutable representation:
>>> list("abcd")
['a', 'b', 'c', 'd']
>>> "".join(list("abcd"))
'abcd'

>>> # Strings are recursive data structures:
>>> type("abc")
"<class 'str'>"
>>> type("abc"[0])
"<class 'str'>"
6 mirip dengan objek
>>> arr = "abcd"
>>> arr[1]
'b'

>>> arr
'abcd'

>>> # Strings are immutable:
>>> arr[1] = "e"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

>>> del arr[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object doesn't support item deletion

>>> # Strings can be unpacked into a list to
>>> # get a mutable representation:
>>> list("abcd")
['a', 'b', 'c', 'd']
>>> "".join(list("abcd"))
'abcd'

>>> # Strings are recursive data structures:
>>> type("abc")
"<class 'str'>"
>>> type("abc"[0])
"<class 'str'>"
2, dan Anda juga dapat menganggapnya sebagai array byte yang tidak dapat diubah

Seperti string,

>>> arr = "abcd"
>>> arr[1]
'b'

>>> arr
'abcd'

>>> # Strings are immutable:
>>> arr[1] = "e"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

>>> del arr[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object doesn't support item deletion

>>> # Strings can be unpacked into a list to
>>> # get a mutable representation:
>>> list("abcd")
['a', 'b', 'c', 'd']
>>> "".join(list("abcd"))
'abcd'

>>> # Strings are recursive data structures:
>>> type("abc")
"<class 'str'>"
>>> type("abc"[0])
"<class 'str'>"
6 memiliki sintaks literalnya sendiri untuk membuat objek dan hemat ruang.
>>> arr = "abcd"
>>> arr[1]
'b'

>>> arr
'abcd'

>>> # Strings are immutable:
>>> arr[1] = "e"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

>>> del arr[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object doesn't support item deletion

>>> # Strings can be unpacked into a list to
>>> # get a mutable representation:
>>> list("abcd")
['a', 'b', 'c', 'd']
>>> "".join(list("abcd"))
'abcd'

>>> # Strings are recursive data structures:
>>> type("abc")
"<class 'str'>"
>>> type("abc"[0])
"<class 'str'>"
6 objek tidak dapat diubah, tetapi tidak seperti string, ada tipe data array byte khusus yang dapat diubah yang disebut
>>> arr = bytes((0, 1, 2, 3))
>>> arr[1]
1

>>> # Bytes literals have their own syntax:
>>> arr
b'\x00\x01\x02\x03'
>>> arr = b"\x00\x01\x02\x03"

>>> # Only valid `bytes` are allowed:
>>> bytes((0, 300))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: bytes must be in range(0, 256)

>>> # Bytes are immutable:
>>> arr[1] = 23
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'bytes' object does not support item assignment

>>> del arr[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'bytes' object doesn't support item deletion
2 yang dapat dibongkar

>>>

>>> arr = bytes((0, 1, 2, 3))
>>> arr[1]
1

>>> # Bytes literals have their own syntax:
>>> arr
b'\x00\x01\x02\x03'
>>> arr = b"\x00\x01\x02\x03"

>>> # Only valid `bytes` are allowed:
>>> bytes((0, 300))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: bytes must be in range(0, 256)

>>> # Bytes are immutable:
>>> arr[1] = 23
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'bytes' object does not support item assignment

>>> del arr[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'bytes' object doesn't support item deletion
_

>>> arr = bytes((0, 1, 2, 3)) >>> arr[1] 1 >>> # Bytes literals have their own syntax: >>> arr b'\x00\x01\x02\x03' >>> arr = b"\x00\x01\x02\x03" >>> # Only valid `bytes` are allowed: >>> bytes((0, 300)) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: bytes must be in range(0, 256) >>> # Bytes are immutable: >>> arr[1] = 23 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'bytes' object does not support item assignment >>> del arr[1] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'bytes' object doesn't support item deletion _2. Array yang Dapat Diubah dari Single Byte

Jenisnya adalah urutan bilangan bulat yang bisa berubah dalam rentang 0 ≤ x ≤ 255. Objek

>>> arr = bytes((0, 1, 2, 3))
>>> arr[1]
1

>>> # Bytes literals have their own syntax:
>>> arr
b'\x00\x01\x02\x03'
>>> arr = b"\x00\x01\x02\x03"

>>> # Only valid `bytes` are allowed:
>>> bytes((0, 300))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: bytes must be in range(0, 256)

>>> # Bytes are immutable:
>>> arr[1] = 23
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'bytes' object does not support item assignment

>>> del arr[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'bytes' object doesn't support item deletion
_2 terkait erat dengan objek
>>> arr = "abcd"
>>> arr[1]
'b'

>>> arr
'abcd'

>>> # Strings are immutable:
>>> arr[1] = "e"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

>>> del arr[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object doesn't support item deletion

>>> # Strings can be unpacked into a list to
>>> # get a mutable representation:
>>> list("abcd")
['a', 'b', 'c', 'd']
>>> "".join(list("abcd"))
'abcd'

>>> # Strings are recursive data structures:
>>> type("abc")
"<class 'str'>"
>>> type("abc"[0])
"<class 'str'>"
6, dengan perbedaan utama adalah bahwa
>>> arr = bytes((0, 1, 2, 3))
>>> arr[1]
1

>>> # Bytes literals have their own syntax:
>>> arr
b'\x00\x01\x02\x03'
>>> arr = b"\x00\x01\x02\x03"

>>> # Only valid `bytes` are allowed:
>>> bytes((0, 300))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: bytes must be in range(0, 256)

>>> # Bytes are immutable:
>>> arr[1] = 23
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'bytes' object does not support item assignment

>>> del arr[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'bytes' object doesn't support item deletion
2 dapat dimodifikasi secara bebas—Anda dapat menimpa elemen, menghapus elemen yang ada, atau menambahkan yang baru. Objek
>>> arr = bytes((0, 1, 2, 3))
>>> arr[1]
1

>>> # Bytes literals have their own syntax:
>>> arr
b'\x00\x01\x02\x03'
>>> arr = b"\x00\x01\x02\x03"

>>> # Only valid `bytes` are allowed:
>>> bytes((0, 300))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: bytes must be in range(0, 256)

>>> # Bytes are immutable:
>>> arr[1] = 23
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'bytes' object does not support item assignment

>>> del arr[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'bytes' object doesn't support item deletion
_2 akan tumbuh dan menyusut

A

>>> arr = bytes((0, 1, 2, 3))
>>> arr[1]
1

>>> # Bytes literals have their own syntax:
>>> arr
b'\x00\x01\x02\x03'
>>> arr = b"\x00\x01\x02\x03"

>>> # Only valid `bytes` are allowed:
>>> bytes((0, 300))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: bytes must be in range(0, 256)

>>> # Bytes are immutable:
>>> arr[1] = 23
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'bytes' object does not support item assignment

>>> del arr[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'bytes' object doesn't support item deletion
_2 dapat diubah kembali menjadi objek
>>> arr = "abcd"
>>> arr[1]
'b'

>>> arr
'abcd'

>>> # Strings are immutable:
>>> arr[1] = "e"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

>>> del arr[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object doesn't support item deletion

>>> # Strings can be unpacked into a list to
>>> # get a mutable representation:
>>> list("abcd")
['a', 'b', 'c', 'd']
>>> "".join(list("abcd"))
'abcd'

>>> # Strings are recursive data structures:
>>> type("abc")
"<class 'str'>"
>>> type("abc"[0])
"<class 'str'>"
6 yang tidak dapat diubah, tetapi ini melibatkan penyalinan data yang disimpan secara penuh—operasi lambat yang memakan waktu O(n) waktu

>>>

>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
0

Array dengan Python. Ringkasan

Ada sejumlah struktur data bawaan yang dapat Anda pilih untuk mengimplementasikan array dengan Python. Di bagian ini, Anda berfokus pada fitur bahasa inti dan struktur data yang disertakan dalam pustaka standar

Jika Anda ingin melampaui pustaka standar Python, maka paket pihak ketiga seperti NumPy dan panda menawarkan berbagai implementasi larik cepat untuk komputasi ilmiah dan ilmu data

Jika Anda ingin membatasi diri Anda pada struktur data array yang disertakan dengan Python, berikut beberapa panduannya

  • Jika Anda perlu menyimpan objek arbitrer, berpotensi dengan tipe data campuran, gunakan

    >>> from collections import ChainMap
    >>> dict1 = {"one": 1, "two": 2}
    >>> dict2 = {"three": 3, "four": 4}
    >>> chain = ChainMap(dict1, dict2)
    
    >>> chain
    ChainMap({'one': 1, 'two': 2}, {'three': 3, 'four': 4})
    
    >>> # ChainMap searches each collection in the chain
    >>> # from left to right until it finds the key (or fails):
    >>> chain["three"]
    3
    >>> chain["one"]
    1
    >>> chain["missing"]
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    KeyError: 'missing'
    
    6 atau
    >>> from types import MappingProxyType
    >>> writable = {"one": 1, "two": 2}
    >>> read_only = MappingProxyType(writable)
    
    >>> # The proxy is read-only:
    >>> read_only["one"]
    1
    >>> read_only["one"] = 23
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: 'mappingproxy' object does not support item assignment
    
    >>> # Updates to the original are reflected in the proxy:
    >>> writable["one"] = 42
    >>> read_only
    mappingproxy({'one': 42, 'two': 2})
    
    4, tergantung pada apakah Anda menginginkan struktur data yang tidak dapat diubah atau tidak

  • Jika Anda memiliki data numerik (integer atau floating-point) dan pengepakan yang ketat serta kinerja penting, cobalah

    >>> import array
    >>> arr = array.array("f", (1.0, 1.5, 2.0, 2.5))
    >>> arr[1]
    1.5
    
    >>> # Arrays have a nice repr:
    >>> arr
    array('f', [1.0, 1.5, 2.0, 2.5])
    
    >>> # Arrays are mutable:
    >>> arr[1] = 23.0
    >>> arr
    array('f', [1.0, 23.0, 2.0, 2.5])
    
    >>> del arr[1]
    >>> arr
    array('f', [1.0, 2.0, 2.5])
    
    >>> arr.append(42.0)
    >>> arr
    array('f', [1.0, 2.0, 2.5, 42.0])
    
    >>> # Arrays are "typed":
    >>> arr[1] = "hello"
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: must be real number, not str
    
    8

  • Jika Anda memiliki data tekstual yang direpresentasikan sebagai karakter Unicode, maka gunakan

    >>> arr = "abcd"
    >>> arr[1]
    'b'
    
    >>> arr
    'abcd'
    
    >>> # Strings are immutable:
    >>> arr[1] = "e"
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: 'str' object does not support item assignment
    
    >>> del arr[1]
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: 'str' object doesn't support item deletion
    
    >>> # Strings can be unpacked into a list to
    >>> # get a mutable representation:
    >>> list("abcd")
    ['a', 'b', 'c', 'd']
    >>> "".join(list("abcd"))
    'abcd'
    
    >>> # Strings are recursive data structures:
    >>> type("abc")
    "<class 'str'>"
    >>> type("abc"[0])
    "<class 'str'>"
    
    2 bawaan Python. Jika Anda memerlukan struktur data seperti string yang dapat diubah, maka gunakan
    >>> from collections import ChainMap
    >>> dict1 = {"one": 1, "two": 2}
    >>> dict2 = {"three": 3, "four": 4}
    >>> chain = ChainMap(dict1, dict2)
    
    >>> chain
    ChainMap({'one': 1, 'two': 2}, {'three': 3, 'four': 4})
    
    >>> # ChainMap searches each collection in the chain
    >>> # from left to right until it finds the key (or fails):
    >>> chain["three"]
    3
    >>> chain["one"]
    1
    >>> chain["missing"]
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    KeyError: 'missing'
    
    6 karakter

  • Jika Anda ingin menyimpan blok byte yang berdekatan, gunakan tipe

    >>> arr = "abcd"
    >>> arr[1]
    'b'
    
    >>> arr
    'abcd'
    
    >>> # Strings are immutable:
    >>> arr[1] = "e"
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: 'str' object does not support item assignment
    
    >>> del arr[1]
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: 'str' object doesn't support item deletion
    
    >>> # Strings can be unpacked into a list to
    >>> # get a mutable representation:
    >>> list("abcd")
    ['a', 'b', 'c', 'd']
    >>> "".join(list("abcd"))
    'abcd'
    
    >>> # Strings are recursive data structures:
    >>> type("abc")
    "<class 'str'>"
    >>> type("abc"[0])
    "<class 'str'>"
    
    6 yang tidak dapat diubah atau
    >>> arr = bytes((0, 1, 2, 3))
    >>> arr[1]
    1
    
    >>> # Bytes literals have their own syntax:
    >>> arr
    b'\x00\x01\x02\x03'
    >>> arr = b"\x00\x01\x02\x03"
    
    >>> # Only valid `bytes` are allowed:
    >>> bytes((0, 300))
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: bytes must be in range(0, 256)
    
    >>> # Bytes are immutable:
    >>> arr[1] = 23
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: 'bytes' object does not support item assignment
    
    >>> del arr[1]
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: 'bytes' object doesn't support item deletion
    
    2 jika Anda memerlukan struktur data yang dapat diubah

Dalam kebanyakan kasus, saya suka memulai dengan

>>> from collections import ChainMap
>>> dict1 = {"one": 1, "two": 2}
>>> dict2 = {"three": 3, "four": 4}
>>> chain = ChainMap(dict1, dict2)

>>> chain
ChainMap({'one': 1, 'two': 2}, {'three': 3, 'four': 4})

>>> # ChainMap searches each collection in the chain
>>> # from left to right until it finds the key (or fails):
>>> chain["three"]
3
>>> chain["one"]
1
>>> chain["missing"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'missing'
6 sederhana. Saya hanya akan mengkhususkan nanti jika kinerja atau ruang penyimpanan menjadi masalah. Sebagian besar waktu, menggunakan struktur data array tujuan umum seperti
>>> from collections import ChainMap
>>> dict1 = {"one": 1, "two": 2}
>>> dict2 = {"three": 3, "four": 4}
>>> chain = ChainMap(dict1, dict2)

>>> chain
ChainMap({'one': 1, 'two': 2}, {'three': 3, 'four': 4})

>>> # ChainMap searches each collection in the chain
>>> # from left to right until it finds the key (or fails):
>>> chain["three"]
3
>>> chain["one"]
1
>>> chain["missing"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'missing'
6 memberi Anda kecepatan pengembangan tercepat dan kenyamanan pemrograman terbanyak

Saya telah menemukan bahwa ini biasanya jauh lebih penting di awal daripada mencoba memeras setiap penurunan kinerja sejak awal

Rekaman, Struktur, dan Objek Transfer Data

Dibandingkan dengan array, struktur data rekaman menyediakan jumlah bidang yang tetap. Setiap bidang dapat memiliki nama dan mungkin juga memiliki jenis yang berbeda

Di bagian ini, Anda akan melihat cara mengimplementasikan record, struct, dan objek data lama biasa di Python hanya menggunakan tipe data dan class bawaan dari library standar

Catatan. Saya menggunakan definisi catatan secara longgar di sini. Sebagai contoh, saya juga akan membahas jenis seperti

>>> from types import MappingProxyType
>>> writable = {"one": 1, "two": 2}
>>> read_only = MappingProxyType(writable)

>>> # The proxy is read-only:
>>> read_only["one"]
1
>>> read_only["one"] = 23
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'mappingproxy' object does not support item assignment

>>> # Updates to the original are reflected in the proxy:
>>> writable["one"] = 42
>>> read_only
mappingproxy({'one': 42, 'two': 2})
4 built-in Python yang mungkin atau mungkin tidak dianggap catatan dalam arti ketat karena mereka tidak menyediakan bidang bernama

Python menawarkan beberapa tipe data yang dapat Anda gunakan untuk mengimplementasikan record, struct, dan objek transfer data. Di bagian ini, Anda akan melihat sekilas setiap penerapan dan karakteristik uniknya. Pada akhirnya, Anda akan menemukan ringkasan dan panduan pengambilan keputusan yang akan membantu Anda membuat pilihan sendiri

Catatan. Tutorial ini diadaptasi dari bab “Common Data Structures in Python” di Python Tricks. Buku. Jika Anda menikmati apa yang Anda baca, maka pastikan untuk memeriksa sisa buku ini

Baiklah, mari kita mulai

Hilangkan iklan

>>> from types import MappingProxyType >>> writable = {"one": 1, "two": 2} >>> read_only = MappingProxyType(writable) >>> # The proxy is read-only: >>> read_only["one"] 1 >>> read_only["one"] = 23 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'mappingproxy' object does not support item assignment >>> # Updates to the original are reflected in the proxy: >>> writable["one"] = 42 >>> read_only mappingproxy({'one': 42, 'two': 2}) _0. Objek Data Sederhana

Seperti disebutkan , kamus Python menyimpan sejumlah objek yang berubah-ubah, masing-masing diidentifikasi dengan kunci unik. Kamus juga sering disebut peta atau larik asosiatif dan memungkinkan pencarian, penyisipan, dan penghapusan objek apa pun yang terkait dengan kunci yang diberikan secara efisien

Menggunakan kamus sebagai tipe data rekaman atau objek data dengan Python dimungkinkan. Kamus mudah dibuat dengan Python karena mereka memiliki gula sintaksis sendiri yang dibangun ke dalam bahasa dalam bentuk literal kamus. Sintaks kamusnya ringkas dan cukup nyaman untuk diketik

Objek data yang dibuat menggunakan kamus dapat berubah, dan ada sedikit perlindungan terhadap nama bidang yang salah eja karena bidang dapat ditambahkan dan dihapus secara bebas kapan saja. Kedua properti ini dapat menimbulkan bug yang mengejutkan, dan selalu ada trade-off yang harus dilakukan antara kenyamanan dan ketahanan kesalahan

>>>

>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
1

>>> from types import MappingProxyType >>> writable = {"one": 1, "two": 2} >>> read_only = MappingProxyType(writable) >>> # The proxy is read-only: >>> read_only["one"] 1 >>> read_only["one"] = 23 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'mappingproxy' object does not support item assignment >>> # Updates to the original are reflected in the proxy: >>> writable["one"] = 42 >>> read_only mappingproxy({'one': 42, 'two': 2}) _4. Grup Objek yang Tidak Dapat Diubah

Tupel Python adalah struktur data langsung untuk mengelompokkan objek arbitrer. Tuple tidak dapat diubah—mereka tidak dapat dimodifikasi setelah dibuat

Dari segi kinerja, tupel membutuhkan lebih dari , dan mereka juga lebih cepat dibuat

Seperti yang Anda lihat dalam pembongkaran bytecode di bawah ini, membangun konstanta tuple membutuhkan opcode

>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
13 tunggal, sementara membangun objek daftar dengan konten yang sama memerlukan beberapa operasi lagi

>>>

>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
2

Namun, Anda tidak boleh terlalu menekankan perbedaan ini. Dalam praktiknya, perbedaan kinerja seringkali dapat diabaikan, dan mencoba memeras kinerja ekstra dari suatu program dengan beralih dari daftar ke tupel kemungkinan akan menjadi pendekatan yang salah.

Kelemahan potensial dari tupel biasa adalah bahwa data yang Anda simpan di dalamnya hanya dapat ditarik keluar dengan mengaksesnya melalui indeks bilangan bulat. Anda tidak dapat memberi nama pada properti individual yang disimpan dalam tuple. Ini dapat memengaruhi keterbacaan kode

Juga, tuple selalu merupakan struktur ad-hoc. sulit untuk memastikan bahwa dua tupel memiliki jumlah bidang yang sama dan properti yang sama disimpan di dalamnya

Hal ini memudahkan untuk memperkenalkan bug slip-of-the-mind, seperti mencampuradukkan urutan bidang. Oleh karena itu, saya akan merekomendasikan agar Anda menyimpan jumlah bidang yang disimpan dalam tupel serendah mungkin

>>>

>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
3

Tulis Kelas Khusus. Lebih Banyak Pekerjaan, Lebih Banyak Kontrol

Kelas memungkinkan Anda menentukan cetak biru yang dapat digunakan kembali untuk objek data guna memastikan setiap objek menyediakan kumpulan bidang yang sama

Menggunakan kelas Python reguler sebagai tipe data rekaman dapat dilakukan, tetapi juga membutuhkan kerja manual untuk mendapatkan fitur kenyamanan dari implementasi lainnya. Misalnya, menambahkan bidang baru ke konstruktor

>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
_14 bersifat verbose dan membutuhkan waktu

Selain itu, representasi string default untuk objek yang dibuat dari kelas khusus tidak terlalu membantu. Untuk memperbaikinya, Anda mungkin harus menambahkan metode Anda sendiri, yang sekali lagi biasanya cukup bertele-tele dan harus diperbarui setiap kali Anda menambahkan bidang baru

Bidang yang disimpan di kelas dapat berubah, dan bidang baru dapat ditambahkan secara bebas, yang mungkin Anda sukai atau tidak. Dimungkinkan untuk memberikan lebih banyak kontrol akses dan membuat bidang hanya-baca menggunakan dekorator, tetapi sekali lagi, ini memerlukan penulisan lebih banyak kode lem

Menulis kelas khusus adalah opsi yang bagus kapan pun Anda ingin menambahkan logika dan perilaku bisnis ke objek rekaman Anda menggunakan metode. Namun, ini berarti bahwa objek ini secara teknis bukan lagi objek data biasa

>>>

>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
4

Hilangkan iklan

>>> import collections >>> d = collections.OrderedDict(one=1, two=2, three=3) >>> d OrderedDict([('one', 1), ('two', 2), ('three', 3)]) >>> d["four"] = 4 >>> d OrderedDict([('one', 1), ('two', 2), ('three', 3), ('four', 4)]) >>> d.keys() odict_keys(['one', 'two', 'three', 'four']) _17. Piton 3. 7+ Kelas Data

Kelas data tersedia di Python 3. 7 dan di atas. Mereka memberikan alternatif yang sangat baik untuk menentukan kelas penyimpanan data Anda sendiri dari awal

Dengan menulis kelas data alih-alih kelas Python biasa, instance objek Anda mendapatkan beberapa fitur berguna di luar kotak yang akan menghemat beberapa pengetikan dan pekerjaan implementasi manual

  • Sintaks untuk mendefinisikan variabel instan lebih pendek, karena Anda tidak perlu mengimplementasikan metode
    >>> import collections
    >>> d = collections.OrderedDict(one=1, two=2, three=3)
    
    >>> d
    OrderedDict([('one', 1), ('two', 2), ('three', 3)])
    
    >>> d["four"] = 4
    >>> d
    OrderedDict([('one', 1), ('two', 2),
                 ('three', 3), ('four', 4)])
    
    >>> d.keys()
    odict_keys(['one', 'two', 'three', 'four'])
    
    18
  • Contoh kelas data Anda secara otomatis mendapatkan representasi string yang terlihat bagus melalui metode
    >>> import collections
    >>> d = collections.OrderedDict(one=1, two=2, three=3)
    
    >>> d
    OrderedDict([('one', 1), ('two', 2), ('three', 3)])
    
    >>> d["four"] = 4
    >>> d
    OrderedDict([('one', 1), ('two', 2),
                 ('three', 3), ('four', 4)])
    
    >>> d.keys()
    odict_keys(['one', 'two', 'three', 'four'])
    
    19 yang dibuat secara otomatis
  • Variabel instan menerima anotasi jenis, membuat kelas data Anda mendokumentasikan diri sampai tingkat tertentu. Ingatlah bahwa anotasi jenis hanyalah petunjuk yang tidak diterapkan tanpa alat pemeriksa jenis yang terpisah

Kelas data biasanya dibuat menggunakan dekorator

>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
20, seperti yang akan Anda lihat pada contoh kode di bawah ini

>>>

>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
5

Untuk mempelajari lebih lanjut tentang kelas data Python, lihat Panduan Utama untuk Kelas Data di Python 3. 7

>>> import collections >>> d = collections.OrderedDict(one=1, two=2, three=3) >>> d OrderedDict([('one', 1), ('two', 2), ('three', 3)]) >>> d["four"] = 4 >>> d OrderedDict([('one', 1), ('two', 2), ('three', 3), ('four', 4)]) >>> d.keys() odict_keys(['one', 'two', 'three', 'four']) _21. Objek Data Nyaman

Kelas

>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
_22 tersedia di Python 2. 6+ menyediakan ekstensi dari tipe data
>>> from types import MappingProxyType
>>> writable = {"one": 1, "two": 2}
>>> read_only = MappingProxyType(writable)

>>> # The proxy is read-only:
>>> read_only["one"]
1
>>> read_only["one"] = 23
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'mappingproxy' object does not support item assignment

>>> # Updates to the original are reflected in the proxy:
>>> writable["one"] = 42
>>> read_only
mappingproxy({'one': 42, 'two': 2})
4 bawaan. Mirip dengan mendefinisikan kelas khusus, menggunakan
>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
22 memungkinkan Anda menentukan cetak biru yang dapat digunakan kembali untuk catatan Anda yang memastikan nama bidang yang benar digunakan

>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
22 objek tidak dapat diubah, seperti tupel biasa. Ini berarti Anda tidak dapat menambahkan kolom baru atau mengubah kolom yang ada setelah instance
>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
22 dibuat

Selain itu,

>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
_22 objek juga.  .  . tupel bernama. Setiap objek yang disimpan di dalamnya dapat diakses melalui pengidentifikasi unik. Ini membebaskan Anda dari keharusan mengingat indeks bilangan bulat atau menggunakan solusi seperti mendefinisikan konstanta bilangan bulat sebagai mnemonik untuk indeks Anda

>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
22 objek diimplementasikan sebagai kelas Python biasa secara internal. Dalam hal penggunaan memori, mereka juga lebih baik daripada kelas biasa dan sama efisiennya dengan memori seperti tupel biasa

>>>

>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
6

>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
22 objek dapat menjadi cara mudah untuk membersihkan kode Anda dan membuatnya lebih mudah dibaca dengan menerapkan struktur yang lebih baik untuk data Anda

Saya menemukan bahwa beralih dari tipe data ad-hoc seperti kamus dengan format tetap ke objek

>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
22 membantu saya mengekspresikan maksud kode saya dengan lebih jelas. Seringkali ketika saya menerapkan refactoring ini, saya secara ajaib menemukan solusi yang lebih baik untuk masalah yang saya hadapi

Menggunakan

>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
_22 objek di atas tupel dan dikte biasa (tidak terstruktur) juga dapat membuat hidup rekan kerja Anda lebih mudah dengan membuat data yang diteruskan mendokumentasikan diri, setidaknya sampai taraf tertentu

>>>

>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
7

>>> import collections >>> d = collections.OrderedDict(one=1, two=2, three=3) >>> d OrderedDict([('one', 1), ('two', 2), ('three', 3)]) >>> d["four"] = 4 >>> d OrderedDict([('one', 1), ('two', 2), ('three', 3), ('four', 4)]) >>> d.keys() odict_keys(['one', 'two', 'three', 'four']) _32. Namedtuple yang ditingkatkan

Ditambahkan dalam Python 3. 6, adalah adik dari kelas

>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
22 di modul
>>> arr = ["one", "two", "three"]
>>> arr[0]
'one'

>>> # Lists have a nice repr:
>>> arr
['one', 'two', 'three']

>>> # Lists are mutable:
>>> arr[1] = "hello"
>>> arr
['one', 'hello', 'three']

>>> del arr[1]
>>> arr
['one', 'three']

>>> # Lists can hold arbitrary data types:
>>> arr.append(23)
>>> arr
['one', 'three', 23]
1. Ini sangat mirip dengan
>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
_22, dengan perbedaan utama adalah sintaks yang diperbarui untuk menentukan jenis catatan baru dan menambahkan dukungan untuk petunjuk jenis

Harap diperhatikan bahwa anotasi jenis tidak diterapkan tanpa alat pemeriksa jenis terpisah seperti mypy. Tetapi bahkan tanpa dukungan alat, mereka dapat memberikan petunjuk yang berguna untuk pemrogram lain (atau sangat membingungkan jika petunjuk jenisnya sudah ketinggalan zaman)

>>>

>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
8

Hilangkan iklan

>>> import collections >>> d = collections.OrderedDict(one=1, two=2, three=3) >>> d OrderedDict([('one', 1), ('two', 2), ('three', 3)]) >>> d["four"] = 4 >>> d OrderedDict([('one', 1), ('two', 2), ('three', 3), ('four', 4)]) >>> d.keys() odict_keys(['one', 'two', 'three', 'four']) _37. Struktur C berseri

Kelas mengonversi antara nilai Python dan struct C yang diserialisasi menjadi objek Python

>>> arr = "abcd"
>>> arr[1]
'b'

>>> arr
'abcd'

>>> # Strings are immutable:
>>> arr[1] = "e"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

>>> del arr[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object doesn't support item deletion

>>> # Strings can be unpacked into a list to
>>> # get a mutable representation:
>>> list("abcd")
['a', 'b', 'c', 'd']
>>> "".join(list("abcd"))
'abcd'

>>> # Strings are recursive data structures:
>>> type("abc")
"<class 'str'>"
>>> type("abc"[0])
"<class 'str'>"
6. Misalnya, dapat digunakan untuk menangani data biner yang disimpan dalam file atau masuk dari koneksi jaringan

Struktur didefinisikan menggunakan bahasa mini berdasarkan yang memungkinkan Anda untuk menentukan pengaturan berbagai tipe data C seperti

>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
40,
>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
41, dan
>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
42 serta varian
>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
43 mereka

Struk berseri jarang digunakan untuk merepresentasikan objek data yang dimaksudkan untuk ditangani murni di dalam kode Python. Mereka dimaksudkan terutama sebagai format pertukaran data daripada sebagai cara menyimpan data dalam memori yang hanya digunakan oleh kode Python

Dalam beberapa kasus, mengemas data primitif ke dalam struct mungkin menggunakan lebih sedikit memori daripada menyimpannya di tipe data lain. Namun, dalam kebanyakan kasus itu akan menjadi pengoptimalan yang cukup maju (dan mungkin tidak perlu).

>>>

>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
9

>>> import collections >>> d = collections.OrderedDict(one=1, two=2, three=3) >>> d OrderedDict([('one', 1), ('two', 2), ('three', 3)]) >>> d["four"] = 4 >>> d OrderedDict([('one', 1), ('two', 2), ('three', 3), ('four', 4)]) >>> d.keys() odict_keys(['one', 'two', 'three', 'four']) _44. Akses Atribut Mewah

Inilah satu lagi pilihan yang sedikit tidak jelas untuk mengimplementasikan objek data dengan Python. . Kelas ini ditambahkan dalam Python 3. 3 dan memberikan akses atribut ke namespace-nya

Ini berarti

>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
_46 contoh mengekspos semua kunci mereka sebagai atribut kelas. Anda dapat menggunakan
>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
47 akses atribut bertitik alih-alih
>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
48 sintaks pengindeksan kurung siku yang digunakan oleh dikt biasa. Semua contoh juga menyertakan
>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
_15 yang bermakna secara default

Seperti namanya,

>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
46 sederhana. Ini pada dasarnya adalah kamus yang memungkinkan akses atribut dan mencetak dengan baik. Atribut dapat ditambahkan, dimodifikasi, dan dihapus dengan bebas

>>>

>>> from collections import defaultdict
>>> dd = defaultdict(list)

>>> # Accessing a missing key creates it and
>>> # initializes it using the default factory,
>>> # i.e. list() in this example:
>>> dd["dogs"].append("Rufus")
>>> dd["dogs"].append("Kathrin")
>>> dd["dogs"].append("Mr Sniffles")

>>> dd["dogs"]
['Rufus', 'Kathrin', 'Mr Sniffles']
0

Catatan, Struktur, dan Objek Data dengan Python. Ringkasan

Seperti yang telah Anda lihat, ada cukup banyak opsi berbeda untuk mengimplementasikan rekaman atau objek data. Jenis apa yang harus Anda gunakan untuk objek data di Python?

  • Jika Anda hanya memiliki beberapa bidang, maka menggunakan objek tupel polos mungkin baik-baik saja jika urutan bidang mudah diingat atau nama bidang berlebihan. Misalnya, pikirkan titik

    >>> import collections
    >>> d = collections.OrderedDict(one=1, two=2, three=3)
    
    >>> d
    OrderedDict([('one', 1), ('two', 2), ('three', 3)])
    
    >>> d["four"] = 4
    >>> d
    OrderedDict([('one', 1), ('two', 2),
                 ('three', 3), ('four', 4)])
    
    >>> d.keys()
    odict_keys(['one', 'two', 'three', 'four'])
    
    _51 dalam ruang tiga dimensi

  • Jika Anda membutuhkan bidang yang tidak dapat diubah, maka tupel biasa,

    >>> import collections
    >>> d = collections.OrderedDict(one=1, two=2, three=3)
    
    >>> d
    OrderedDict([('one', 1), ('two', 2), ('three', 3)])
    
    >>> d["four"] = 4
    >>> d
    OrderedDict([('one', 1), ('two', 2),
                 ('three', 3), ('four', 4)])
    
    >>> d.keys()
    odict_keys(['one', 'two', 'three', 'four'])
    
    21, dan
    >>> import collections
    >>> d = collections.OrderedDict(one=1, two=2, three=3)
    
    >>> d
    OrderedDict([('one', 1), ('two', 2), ('three', 3)])
    
    >>> d["four"] = 4
    >>> d
    OrderedDict([('one', 1), ('two', 2),
                 ('three', 3), ('four', 4)])
    
    >>> d.keys()
    odict_keys(['one', 'two', 'three', 'four'])
    
    32 adalah opsi yang bagus

  • Jika Anda perlu mengunci nama bidang untuk menghindari kesalahan ketik, maka

    >>> import collections
    >>> d = collections.OrderedDict(one=1, two=2, three=3)
    
    >>> d
    OrderedDict([('one', 1), ('two', 2), ('three', 3)])
    
    >>> d["four"] = 4
    >>> d
    OrderedDict([('one', 1), ('two', 2),
                 ('three', 3), ('four', 4)])
    
    >>> d.keys()
    odict_keys(['one', 'two', 'three', 'four'])
    
    21 dan
    >>> import collections
    >>> d = collections.OrderedDict(one=1, two=2, three=3)
    
    >>> d
    OrderedDict([('one', 1), ('two', 2), ('three', 3)])
    
    >>> d["four"] = 4
    >>> d
    OrderedDict([('one', 1), ('two', 2),
                 ('three', 3), ('four', 4)])
    
    >>> d.keys()
    odict_keys(['one', 'two', 'three', 'four'])
    
    32 adalah teman Anda

  • Jika Anda ingin menjaga hal-hal sederhana, maka objek kamus biasa mungkin menjadi pilihan yang baik karena sintaks nyaman yang sangat mirip dengan JSON

  • Jika Anda memerlukan kontrol penuh atas struktur data Anda, inilah waktunya untuk menulis kelas khusus dengan penyetel dan pengambil

  • Jika Anda perlu menambahkan perilaku (metode) ke objek, maka Anda harus menulis kelas khusus, baik dari awal, atau menggunakan dekorator

    >>> import collections
    >>> d = collections.OrderedDict(one=1, two=2, three=3)
    
    >>> d
    OrderedDict([('one', 1), ('two', 2), ('three', 3)])
    
    >>> d["four"] = 4
    >>> d
    OrderedDict([('one', 1), ('two', 2),
                 ('three', 3), ('four', 4)])
    
    >>> d.keys()
    odict_keys(['one', 'two', 'three', 'four'])
    
    57, atau dengan memperluas
    >>> import collections
    >>> d = collections.OrderedDict(one=1, two=2, three=3)
    
    >>> d
    OrderedDict([('one', 1), ('two', 2), ('three', 3)])
    
    >>> d["four"] = 4
    >>> d
    OrderedDict([('one', 1), ('two', 2),
                 ('three', 3), ('four', 4)])
    
    >>> d.keys()
    odict_keys(['one', 'two', 'three', 'four'])
    
    21 atau
    >>> import collections
    >>> d = collections.OrderedDict(one=1, two=2, three=3)
    
    >>> d
    OrderedDict([('one', 1), ('two', 2), ('three', 3)])
    
    >>> d["four"] = 4
    >>> d
    OrderedDict([('one', 1), ('two', 2),
                 ('three', 3), ('four', 4)])
    
    >>> d.keys()
    odict_keys(['one', 'two', 'three', 'four'])
    
    32

  • Jika Anda perlu mengemas data dengan erat untuk membuat serialisasi ke disk atau mengirimkannya melalui jaringan, inilah saatnya untuk membaca

    >>> import collections
    >>> d = collections.OrderedDict(one=1, two=2, three=3)
    
    >>> d
    OrderedDict([('one', 1), ('two', 2), ('three', 3)])
    
    >>> d["four"] = 4
    >>> d
    OrderedDict([('one', 1), ('two', 2),
                 ('three', 3), ('four', 4)])
    
    >>> d.keys()
    odict_keys(['one', 'two', 'three', 'four'])
    
    37 karena ini adalah kasus penggunaan yang bagus untuk itu

Jika Anda mencari pilihan default yang aman, maka rekomendasi umum saya untuk mengimplementasikan record biasa, struct, atau objek data di Python adalah menggunakan

>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
21 di Python 2. x dan adiknya,
>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
32 dengan Python 3

Set dan Multiset

Di bagian ini, Anda akan melihat cara mengimplementasikan struktur data set dan multiset (bag) yang dapat berubah dan tidak dapat diubah di Python menggunakan tipe dan kelas data bawaan dari pustaka standar

Set adalah kumpulan objek yang tidak terurut yang tidak memungkinkan elemen duplikat. Biasanya, himpunan digunakan untuk dengan cepat menguji nilai keanggotaan dalam himpunan, untuk menyisipkan atau menghapus nilai baru dari himpunan, dan untuk menghitung penyatuan atau perpotongan dua himpunan.

Dalam implementasi set yang tepat, pengujian keanggotaan diharapkan berjalan dalam waktu O(1) yang cepat. Operasi penyatuan, persimpangan, perbedaan, dan subset harus memakan waktu rata-rata O(n). Implementasi set yang termasuk dalam pustaka standar Python mengikuti karakteristik kinerja ini

Sama seperti kamus, set mendapatkan perlakuan khusus dengan Python dan memiliki beberapa gula sintaksis yang membuatnya mudah dibuat. Misalnya, sintaks ekspresi set kurung kurawal dan memungkinkan Anda untuk dengan mudah menentukan instance set baru

>>> from collections import defaultdict
>>> dd = defaultdict(list)

>>> # Accessing a missing key creates it and
>>> # initializes it using the default factory,
>>> # i.e. list() in this example:
>>> dd["dogs"].append("Rufus")
>>> dd["dogs"].append("Kathrin")
>>> dd["dogs"].append("Mr Sniffles")

>>> dd["dogs"]
['Rufus', 'Kathrin', 'Mr Sniffles']
1

Tetapi berhati-hatilah. Untuk membuat set kosong, Anda harus memanggil konstruktor

>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
63. Menggunakan kurung kurawal kosong (
>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
64) bersifat ambigu dan akan membuat kamus kosong sebagai gantinya

Python dan pustaka standarnya menyediakan beberapa set implementasi. Mari kita lihat mereka

Hilangkan iklan

>>> import collections >>> d = collections.OrderedDict(one=1, two=2, three=3) >>> d OrderedDict([('one', 1), ('two', 2), ('three', 3)]) >>> d["four"] = 4 >>> d OrderedDict([('one', 1), ('two', 2), ('three', 3), ('four', 4)]) >>> d.keys() odict_keys(['one', 'two', 'three', 'four']) _65. Perangkat Masuk Anda

Jenisnya adalah implementasi set bawaan di Python. Ini bisa berubah dan memungkinkan penyisipan dan penghapusan elemen secara dinamis

Set Python didukung oleh tipe data

>>> from types import MappingProxyType
>>> writable = {"one": 1, "two": 2}
>>> read_only = MappingProxyType(writable)

>>> # The proxy is read-only:
>>> read_only["one"]
1
>>> read_only["one"] = 23
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'mappingproxy' object does not support item assignment

>>> # Updates to the original are reflected in the proxy:
>>> writable["one"] = 42
>>> read_only
mappingproxy({'one': 42, 'two': 2})
0 dan berbagi karakteristik kinerja yang sama. Objek apa pun dapat disimpan dalam satu set

>>>

>>> from collections import defaultdict
>>> dd = defaultdict(list)

>>> # Accessing a missing key creates it and
>>> # initializes it using the default factory,
>>> # i.e. list() in this example:
>>> dd["dogs"].append("Rufus")
>>> dd["dogs"].append("Kathrin")
>>> dd["dogs"].append("Mr Sniffles")

>>> dd["dogs"]
['Rufus', 'Kathrin', 'Mr Sniffles']
2

>>> import collections >>> d = collections.OrderedDict(one=1, two=2, three=3) >>> d OrderedDict([('one', 1), ('two', 2), ('three', 3)]) >>> d["four"] = 4 >>> d OrderedDict([('one', 1), ('two', 2), ('three', 3), ('four', 4)]) >>> d.keys() odict_keys(['one', 'two', 'three', 'four']) _68. Set yang tidak dapat diubah

Kelas mengimplementasikan versi

>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
65 yang tidak dapat diubah yang tidak dapat diubah setelah dibuat

>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
68 objek bersifat statis dan hanya mengizinkan operasi kueri pada elemennya, bukan penyisipan atau penghapusan. Karena objek
>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
_68 bersifat statis dan hashable, mereka dapat digunakan sebagai kunci kamus atau sebagai elemen dari kumpulan lain, sesuatu yang tidak mungkin dilakukan dengan objek biasa (dapat diubah)
>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
65

>>>

>>> from collections import defaultdict
>>> dd = defaultdict(list)

>>> # Accessing a missing key creates it and
>>> # initializes it using the default factory,
>>> # i.e. list() in this example:
>>> dd["dogs"].append("Rufus")
>>> dd["dogs"].append("Kathrin")
>>> dd["dogs"].append("Mr Sniffles")

>>> dd["dogs"]
['Rufus', 'Kathrin', 'Mr Sniffles']
3

>>> import collections >>> d = collections.OrderedDict(one=1, two=2, three=3) >>> d OrderedDict([('one', 1), ('two', 2), ('three', 3)]) >>> d["four"] = 4 >>> d OrderedDict([('one', 1), ('two', 2), ('three', 3), ('four', 4)]) >>> d.keys() odict_keys(['one', 'two', 'three', 'four']) _74. Multiset

Kelas di perpustakaan standar Python mengimplementasikan multiset, atau tas, tipe yang memungkinkan elemen di set memiliki lebih dari satu kejadian

Ini berguna jika Anda perlu melacak tidak hanya jika suatu elemen adalah bagian dari kumpulan, tetapi juga berapa kali itu disertakan dalam kumpulan

>>>

>>> from collections import defaultdict
>>> dd = defaultdict(list)

>>> # Accessing a missing key creates it and
>>> # initializes it using the default factory,
>>> # i.e. list() in this example:
>>> dd["dogs"].append("Rufus")
>>> dd["dogs"].append("Kathrin")
>>> dd["dogs"].append("Mr Sniffles")

>>> dd["dogs"]
['Rufus', 'Kathrin', 'Mr Sniffles']
4

Satu peringatan untuk kelas

>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
_76 adalah Anda harus berhati-hati saat menghitung jumlah elemen dalam objek
>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
76. Memanggil
>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
_78 mengembalikan jumlah elemen unik dalam multiset, sedangkan jumlah total elemen dapat diambil menggunakan
>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
79

>>>

>>> from collections import defaultdict
>>> dd = defaultdict(list)

>>> # Accessing a missing key creates it and
>>> # initializes it using the default factory,
>>> # i.e. list() in this example:
>>> dd["dogs"].append("Rufus")
>>> dd["dogs"].append("Kathrin")
>>> dd["dogs"].append("Mr Sniffles")

>>> dd["dogs"]
['Rufus', 'Kathrin', 'Mr Sniffles']
5

Set dan Multiset dengan Python. Ringkasan

Set adalah struktur data lain yang berguna dan umum digunakan yang disertakan dengan Python dan pustaka standarnya. Berikut adalah beberapa panduan untuk memutuskan mana yang akan digunakan

  • Jika Anda membutuhkan set yang bisa berubah, gunakan tipe
    >>> import collections
    >>> d = collections.OrderedDict(one=1, two=2, three=3)
    
    >>> d
    OrderedDict([('one', 1), ('two', 2), ('three', 3)])
    
    >>> d["four"] = 4
    >>> d
    OrderedDict([('one', 1), ('two', 2),
                 ('three', 3), ('four', 4)])
    
    >>> d.keys()
    odict_keys(['one', 'two', 'three', 'four'])
    
    65 bawaan
  • Jika Anda memerlukan objek hashable yang dapat digunakan sebagai kamus atau set kunci, gunakan
    >>> import collections
    >>> d = collections.OrderedDict(one=1, two=2, three=3)
    
    >>> d
    OrderedDict([('one', 1), ('two', 2), ('three', 3)])
    
    >>> d["four"] = 4
    >>> d
    OrderedDict([('one', 1), ('two', 2),
                 ('three', 3), ('four', 4)])
    
    >>> d.keys()
    odict_keys(['one', 'two', 'three', 'four'])
    
    68
  • Jika Anda memerlukan struktur data multiset, atau tas, gunakan
    >>> import collections
    >>> d = collections.OrderedDict(one=1, two=2, three=3)
    
    >>> d
    OrderedDict([('one', 1), ('two', 2), ('three', 3)])
    
    >>> d["four"] = 4
    >>> d
    OrderedDict([('one', 1), ('two', 2),
                 ('three', 3), ('four', 4)])
    
    >>> d.keys()
    odict_keys(['one', 'two', 'three', 'four'])
    
    74

Tumpukan (LIFO)

A adalah kumpulan objek yang mendukung semantik Last-In/First-Out (LIFO) cepat untuk penyisipan dan penghapusan. Tidak seperti daftar atau larik, tumpukan biasanya tidak mengizinkan akses acak ke objek yang dikandungnya. Operasi insert dan delete juga sering disebut push and pop

Analogi dunia nyata yang berguna untuk struktur data tumpukan adalah tumpukan pelat. Pelat baru ditambahkan ke bagian atas tumpukan, dan karena pelat berharga dan berat, hanya pelat paling atas yang dapat dipindahkan. Dengan kata lain, pelat terakhir pada tumpukan harus menjadi yang pertama dilepas (LIFO). Untuk mencapai pelat yang lebih rendah di tumpukan, pelat paling atas harus dilepas satu per satu

Dari segi kinerja, implementasi tumpukan yang tepat diharapkan membutuhkan waktu O(1) untuk operasi penyisipan dan penghapusan

Tumpukan memiliki berbagai kegunaan dalam algoritma. Misalnya, mereka digunakan dalam penguraian bahasa serta manajemen memori runtime, yang bergantung pada tumpukan panggilan. Algoritme pendek dan indah menggunakan tumpukan adalah pencarian pertama-dalam (DFS) pada pohon atau struktur data grafik

Python dikirimkan dengan beberapa implementasi tumpukan yang masing-masing memiliki karakteristik yang sedikit berbeda. Mari kita lihat dan bandingkan karakteristiknya

Hilangkan iklan

>>> from collections import ChainMap >>> dict1 = {"one": 1, "two": 2} >>> dict2 = {"three": 3, "four": 4} >>> chain = ChainMap(dict1, dict2) >>> chain ChainMap({'one': 1, 'two': 2}, {'three': 3, 'four': 4}) >>> # ChainMap searches each collection in the chain >>> # from left to right until it finds the key (or fails): >>> chain["three"] 3 >>> chain["one"] 1 >>> chain["missing"] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'missing' _6. Sederhana, Tumpukan Bawaan

Tipe

>>> from collections import ChainMap
>>> dict1 = {"one": 1, "two": 2}
>>> dict2 = {"three": 3, "four": 4}
>>> chain = ChainMap(dict1, dict2)

>>> chain
ChainMap({'one': 1, 'two': 2}, {'three': 3, 'four': 4})

>>> # ChainMap searches each collection in the chain
>>> # from left to right until it finds the key (or fails):
>>> chain["three"]
3
>>> chain["one"]
1
>>> chain["missing"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'missing'
6 bawaan Python karena mendukung operasi push dan pop dalam waktu O(1) diamortisasi

Daftar Python diimplementasikan sebagai array dinamis secara internal, yang berarti mereka terkadang perlu mengubah ukuran ruang penyimpanan untuk elemen yang disimpan di dalamnya saat elemen ditambahkan atau dihapus. Daftar tersebut mengalokasikan penyimpanan pendukungnya secara berlebihan sehingga tidak setiap push atau pop memerlukan pengubahan ukuran. Akibatnya, Anda mendapatkan kompleksitas waktu O(1) diamortisasi untuk operasi ini

Sisi negatifnya adalah ini membuat kinerjanya kurang konsisten dibandingkan penyisipan dan penghapusan O(1) stabil yang disediakan oleh implementasi berbasis daftar tertaut (seperti yang akan Anda lihat di bawah dengan

>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
85). Di sisi lain, daftar menyediakan akses acak cepat O(1) waktu ke elemen di tumpukan, dan ini bisa menjadi keuntungan tambahan

Ada peringatan kinerja penting yang harus Anda ketahui saat menggunakan daftar sebagai tumpukan. Untuk mendapatkan kinerja O(1) diamortisasi untuk penyisipan dan penghapusan, item baru harus ditambahkan ke akhir daftar dengan metode

>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
86 dan dihapus lagi dari akhir menggunakan
>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
87. Untuk kinerja optimal, tumpukan berdasarkan daftar Python harus tumbuh ke indeks yang lebih tinggi dan menyusut ke indeks yang lebih rendah

Menambah dan menghapus dari depan jauh lebih lambat dan membutuhkan waktu O(n), karena elemen yang ada harus digeser untuk memberi ruang bagi elemen baru. Ini adalah antipola kinerja yang harus Anda hindari sebisa mungkin

>>>

>>> from collections import defaultdict
>>> dd = defaultdict(list)

>>> # Accessing a missing key creates it and
>>> # initializes it using the default factory,
>>> # i.e. list() in this example:
>>> dd["dogs"].append("Rufus")
>>> dd["dogs"].append("Kathrin")
>>> dd["dogs"].append("Mr Sniffles")

>>> dd["dogs"]
['Rufus', 'Kathrin', 'Mr Sniffles']
6

>>> import collections >>> d = collections.OrderedDict(one=1, two=2, three=3) >>> d OrderedDict([('one', 1), ('two', 2), ('three', 3)]) >>> d["four"] = 4 >>> d OrderedDict([('one', 1), ('two', 2), ('three', 3), ('four', 4)]) >>> d.keys() odict_keys(['one', 'two', 'three', 'four']) _85. Tumpukan Cepat dan Kuat

Kelas mengimplementasikan a yang mendukung penambahan dan penghapusan elemen dari salah satu ujung dalam waktu O(1) (tidak diamortisasi). Karena deques mendukung penambahan dan penghapusan elemen dari kedua ujung dengan sama baiknya, mereka dapat berfungsi baik sebagai antrian maupun sebagai tumpukan

Objek

>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
89 Python diimplementasikan sebagai , yang memberi mereka kinerja yang sangat baik dan konsisten untuk memasukkan dan menghapus elemen tetapi kinerja O(n) yang buruk untuk mengakses elemen secara acak di tengah tumpukan

Secara keseluruhan, jika Anda mencari struktur data tumpukan di pustaka standar Python yang memiliki karakteristik kinerja implementasi daftar tertaut

>>>

>>> from collections import defaultdict
>>> dd = defaultdict(list)

>>> # Accessing a missing key creates it and
>>> # initializes it using the default factory,
>>> # i.e. list() in this example:
>>> dd["dogs"].append("Rufus")
>>> dd["dogs"].append("Kathrin")
>>> dd["dogs"].append("Mr Sniffles")

>>> dd["dogs"]
['Rufus', 'Kathrin', 'Mr Sniffles']
7

>>> import collections >>> d = collections.OrderedDict(one=1, two=2, three=3) >>> d OrderedDict([('one', 1), ('two', 2), ('three', 3)]) >>> d["four"] = 4 >>> d OrderedDict([('one', 1), ('two', 2), ('three', 3), ('four', 4)]) >>> d.keys() odict_keys(['one', 'two', 'three', 'four']) _92. Mengunci Semantik untuk Komputasi Paralel

Implementasi tumpukan di pustaka standar Python disinkronkan dan menyediakan semantik penguncian untuk mendukung banyak produsen dan konsumen secara bersamaan

Selain

>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
_93, modul
>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
95 berisi beberapa kelas lain yang menerapkan antrian multi-produsen, multi-konsumen yang berguna untuk komputasi paralel

Bergantung pada kasus penggunaan Anda, semantik penguncian mungkin berguna, atau mungkin menimbulkan biaya tambahan yang tidak dibutuhkan. Dalam hal ini, Anda akan lebih baik menggunakan

>>> from collections import ChainMap
>>> dict1 = {"one": 1, "two": 2}
>>> dict2 = {"three": 3, "four": 4}
>>> chain = ChainMap(dict1, dict2)

>>> chain
ChainMap({'one': 1, 'two': 2}, {'three': 3, 'four': 4})

>>> # ChainMap searches each collection in the chain
>>> # from left to right until it finds the key (or fails):
>>> chain["three"]
3
>>> chain["one"]
1
>>> chain["missing"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'missing'
6 atau
>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
89 sebagai tumpukan tujuan umum

>>> ________29______8

Implementasi Stack dengan Python. Ringkasan

Seperti yang Anda lihat, Python dikirimkan dengan beberapa implementasi untuk struktur data tumpukan. Semuanya memiliki karakteristik yang sedikit berbeda serta pertukaran kinerja dan penggunaan

Jika Anda tidak mencari dukungan pemrosesan paralel (atau jika Anda tidak ingin menangani penguncian dan pembukaan kunci secara manual), maka pilihan Anda adalah tipe

>>> from collections import ChainMap
>>> dict1 = {"one": 1, "two": 2}
>>> dict2 = {"three": 3, "four": 4}
>>> chain = ChainMap(dict1, dict2)

>>> chain
ChainMap({'one': 1, 'two': 2}, {'three': 3, 'four': 4})

>>> # ChainMap searches each collection in the chain
>>> # from left to right until it finds the key (or fails):
>>> chain["three"]
3
>>> chain["one"]
1
>>> chain["missing"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'missing'
6 bawaan atau
>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
85. Perbedaannya terletak pada struktur data yang digunakan di balik layar dan kemudahan penggunaan secara keseluruhan

>>> from collections import ChainMap
>>> dict1 = {"one": 1, "two": 2}
>>> dict2 = {"three": 3, "four": 4}
>>> chain = ChainMap(dict1, dict2)

>>> chain
ChainMap({'one': 1, 'two': 2}, {'three': 3, 'four': 4})

>>> # ChainMap searches each collection in the chain
>>> # from left to right until it finds the key (or fails):
>>> chain["three"]
3
>>> chain["one"]
1
>>> chain["missing"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'missing'
6 didukung oleh larik dinamis, yang membuatnya bagus untuk akses acak yang cepat tetapi memerlukan pengubahan ukuran sesekali saat elemen ditambahkan atau dihapus

Daftar mengalokasikan penyimpanan pendukungnya secara berlebihan sehingga tidak setiap push atau pop memerlukan pengubahan ukuran, dan Anda mendapatkan kompleksitas waktu O(1) yang diamortisasi untuk operasi ini. Namun Anda harus berhati-hati untuk hanya memasukkan dan mengeluarkan item menggunakan

>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
86 dan
>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
87. Jika tidak, kinerja melambat menjadi O(n)

>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
85 didukung oleh daftar tertaut ganda, yang mengoptimalkan penambahan dan penghapusan di kedua ujungnya dan memberikan kinerja O(1) yang konsisten untuk operasi ini. Tidak hanya kinerjanya yang lebih stabil, kelas
>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
89 juga lebih mudah digunakan karena Anda tidak perlu khawatir menambahkan atau menghapus item dari ujung yang salah

Singkatnya,

>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
_85 adalah pilihan yang sangat baik untuk mengimplementasikan tumpukan (antrian LIFO) dengan Python

Hilangkan iklan

Antrean (FIFO)

Di bagian ini, Anda akan melihat cara mengimplementasikan struktur data antrean First-In/First-Out (FIFO) hanya menggunakan tipe dan kelas data bawaan dari pustaka standar Python

A adalah kumpulan objek yang mendukung semantik FIFO cepat untuk penyisipan dan penghapusan. Operasi insert dan delete terkadang disebut enqueue dan dequeue. Tidak seperti daftar atau larik, antrean biasanya tidak mengizinkan akses acak ke objek yang ada di dalamnya

Inilah analogi dunia nyata untuk antrean FIFO

Bayangkan barisan Pythonista menunggu untuk mengambil lencana konferensi mereka pada hari pertama pendaftaran PyCon. Saat orang baru memasuki tempat konferensi dan mengantre untuk menerima lencana mereka, mereka bergabung dengan antrean (enqueue) di belakang antrean. Pengembang menerima lencana dan tas swag konferensi mereka dan kemudian keluar dari antrean (dequeue) di depan antrean

Cara lain untuk mengingat karakteristik struktur data antrian adalah dengan menganggapnya sebagai sebuah pipa. Anda menambahkan bola ping-pong ke salah satu ujungnya, dan bola itu bergerak ke ujung lainnya, tempat Anda membuangnya. Saat bola berada dalam antrean (pipa logam padat), Anda tidak bisa mendapatkannya. Satu-satunya cara untuk berinteraksi dengan bola dalam antrean adalah menambahkan yang baru di belakang pipa (enqueue) atau menghapusnya di depan (dequeue)

Antrian mirip dengan tumpukan. Perbedaan di antara mereka terletak pada bagaimana item dihapus. Dengan antrean, Anda menghapus item yang paling baru ditambahkan (FIFO) tetapi dengan tumpukan, Anda menghapus item yang paling baru ditambahkan (LIFO)

Dari segi kinerja, implementasi antrean yang tepat diharapkan membutuhkan waktu O(1) untuk operasi penyisipan dan penghapusan. Ini adalah dua operasi utama yang dilakukan pada antrian, dan dalam penerapan yang benar, keduanya harus cepat

Antrian memiliki berbagai aplikasi dalam algoritme dan sering kali membantu memecahkan masalah penjadwalan dan pemrograman paralel. Algoritme singkat dan indah menggunakan antrian adalah pencarian pertama luas (BFS) pada pohon atau struktur data grafik

Algoritma penjadwalan sering menggunakan antrian prioritas secara internal. Ini adalah antrian khusus. Alih-alih mengambil elemen berikutnya dengan waktu penyisipan, a mengambil elemen dengan prioritas tertinggi. Prioritas masing-masing elemen ditentukan oleh antrian berdasarkan urutan yang diterapkan pada kunci mereka

Namun, antrean reguler tidak akan menyusun ulang item yang dibawanya. Sama seperti dalam contoh pipa, Anda mengeluarkan apa yang Anda masukkan, dan dalam urutan yang persis seperti itu

Python dikirimkan dengan beberapa implementasi antrian yang masing-masing memiliki karakteristik yang sedikit berbeda. Mari kita tinjau

>>> from collections import ChainMap >>> dict1 = {"one": 1, "two": 2} >>> dict2 = {"three": 3, "four": 4} >>> chain = ChainMap(dict1, dict2) >>> chain ChainMap({'one': 1, 'two': 2}, {'three': 3, 'four': 4}) >>> # ChainMap searches each collection in the chain >>> # from left to right until it finds the key (or fails): >>> chain["three"] 3 >>> chain["one"] 1 >>> chain["missing"] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'missing' _6. Antrian yang sangat lambat

Itu mungkin, tetapi ini tidak ideal dari perspektif kinerja. Daftar cukup lambat untuk tujuan ini karena menyisipkan atau menghapus elemen di awal memerlukan pemindahan semua elemen lainnya satu per satu, membutuhkan waktu O(n)

Oleh karena itu, saya tidak akan merekomendasikan menggunakan

>>> from collections import ChainMap
>>> dict1 = {"one": 1, "two": 2}
>>> dict2 = {"three": 3, "four": 4}
>>> chain = ChainMap(dict1, dict2)

>>> chain
ChainMap({'one': 1, 'two': 2}, {'three': 3, 'four': 4})

>>> # ChainMap searches each collection in the chain
>>> # from left to right until it finds the key (or fails):
>>> chain["three"]
3
>>> chain["one"]
1
>>> chain["missing"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'missing'
6 sebagai antrian darurat di Python kecuali jika Anda hanya berurusan dengan sejumlah kecil elemen

>>>

>>> from collections import defaultdict
>>> dd = defaultdict(list)

>>> # Accessing a missing key creates it and
>>> # initializes it using the default factory,
>>> # i.e. list() in this example:
>>> dd["dogs"].append("Rufus")
>>> dd["dogs"].append("Kathrin")
>>> dd["dogs"].append("Mr Sniffles")

>>> dd["dogs"]
['Rufus', 'Kathrin', 'Mr Sniffles']
9

>>> import collections >>> d = collections.OrderedDict(one=1, two=2, three=3) >>> d OrderedDict([('one', 1), ('two', 2), ('three', 3)]) >>> d["four"] = 4 >>> d OrderedDict([('one', 1), ('two', 2), ('three', 3), ('four', 4)]) >>> d.keys() odict_keys(['one', 'two', 'three', 'four']) _85. Antrian Cepat dan Kuat

Kelas

>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
_89 mengimplementasikan antrian berujung ganda yang mendukung penambahan dan penghapusan elemen dari salah satu ujung dalam waktu O(1) (tidak diamortisasi). Karena deques mendukung penambahan dan penghapusan elemen dari kedua ujung dengan sama baiknya, mereka dapat berfungsi baik sebagai antrian maupun sebagai tumpukan

Objek

>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
89 Python diimplementasikan sebagai daftar tertaut ganda. Ini memberi mereka kinerja yang sangat baik dan konsisten untuk memasukkan dan menghapus elemen, tetapi kinerja O(n) yang buruk untuk mengakses elemen secara acak di tengah tumpukan

Akibatnya,

>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
_85 adalah pilihan default yang bagus jika Anda mencari struktur data antrian di pustaka standar Python

>>>

>>> from collections import ChainMap
>>> dict1 = {"one": 1, "two": 2}
>>> dict2 = {"three": 3, "four": 4}
>>> chain = ChainMap(dict1, dict2)

>>> chain
ChainMap({'one': 1, 'two': 2}, {'three': 3, 'four': 4})

>>> # ChainMap searches each collection in the chain
>>> # from left to right until it finds the key (or fails):
>>> chain["three"]
3
>>> chain["one"]
1
>>> chain["missing"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'missing'
0

>>> from collections import defaultdict >>> dd = defaultdict(list) >>> # Accessing a missing key creates it and >>> # initializes it using the default factory, >>> # i.e. list() in this example: >>> dd["dogs"].append("Rufus") >>> dd["dogs"].append("Kathrin") >>> dd["dogs"].append("Mr Sniffles") >>> dd["dogs"] ['Rufus', 'Kathrin', 'Mr Sniffles'] _13. Mengunci Semantik untuk Komputasi Paralel

Implementasi di pustaka standar Python disinkronkan dan menyediakan semantik penguncian untuk mendukung beberapa produsen dan konsumen secara bersamaan

Modul

>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
_95 berisi beberapa kelas lain yang mengimplementasikan antrean multi-produsen, multi-konsumen yang berguna untuk komputasi paralel

Bergantung pada kasus penggunaan Anda, semantik penguncian mungkin berguna atau hanya menimbulkan biaya overhead yang tidak dibutuhkan. Dalam hal ini, sebaiknya Anda menggunakan

>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
85 sebagai antrean tujuan umum

>>>

>>> from collections import ChainMap
>>> dict1 = {"one": 1, "two": 2}
>>> dict2 = {"three": 3, "four": 4}
>>> chain = ChainMap(dict1, dict2)

>>> chain
ChainMap({'one': 1, 'two': 2}, {'three': 3, 'four': 4})

>>> # ChainMap searches each collection in the chain
>>> # from left to right until it finds the key (or fails):
>>> chain["three"]
3
>>> chain["one"]
1
>>> chain["missing"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'missing'
1

>>> from collections import defaultdict >>> dd = defaultdict(list) >>> # Accessing a missing key creates it and >>> # initializes it using the default factory, >>> # i.e. list() in this example: >>> dd["dogs"].append("Rufus") >>> dd["dogs"].append("Kathrin") >>> dd["dogs"].append("Mr Sniffles") >>> dd["dogs"] ['Rufus', 'Kathrin', 'Mr Sniffles'] _17. Antrean Pekerjaan Bersama

adalah implementasi antrean pekerjaan bersama yang memungkinkan item antrean diproses secara paralel oleh beberapa pekerja bersamaan. Paralelisasi berbasis proses populer di CPython karena kunci juru bahasa global (GIL) yang mencegah beberapa bentuk eksekusi paralel pada satu proses juru bahasa

Sebagai implementasi antrean khusus yang dimaksudkan untuk berbagi data antar proses,

>>> from collections import defaultdict
>>> dd = defaultdict(list)

>>> # Accessing a missing key creates it and
>>> # initializes it using the default factory,
>>> # i.e. list() in this example:
>>> dd["dogs"].append("Rufus")
>>> dd["dogs"].append("Kathrin")
>>> dd["dogs"].append("Mr Sniffles")

>>> dd["dogs"]
['Rufus', 'Kathrin', 'Mr Sniffles']
17 mempermudah pendistribusian pekerjaan ke berbagai proses untuk mengatasi batasan GIL. Jenis antrean ini dapat menyimpan dan mentransfer objek yang dapat diawetkan melintasi batas proses

>>>

>>> from collections import ChainMap
>>> dict1 = {"one": 1, "two": 2}
>>> dict2 = {"three": 3, "four": 4}
>>> chain = ChainMap(dict1, dict2)

>>> chain
ChainMap({'one': 1, 'two': 2}, {'three': 3, 'four': 4})

>>> # ChainMap searches each collection in the chain
>>> # from left to right until it finds the key (or fails):
>>> chain["three"]
3
>>> chain["one"]
1
>>> chain["missing"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'missing'
2

Antrean dengan Python. Ringkasan

Python menyertakan beberapa implementasi antrian sebagai bagian dari bahasa inti dan pustaka standarnya

>>> from collections import ChainMap
>>> dict1 = {"one": 1, "two": 2}
>>> dict2 = {"three": 3, "four": 4}
>>> chain = ChainMap(dict1, dict2)

>>> chain
ChainMap({'one': 1, 'two': 2}, {'three': 3, 'four': 4})

>>> # ChainMap searches each collection in the chain
>>> # from left to right until it finds the key (or fails):
>>> chain["three"]
3
>>> chain["one"]
1
>>> chain["missing"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'missing'
6 objek dapat digunakan sebagai antrian, tetapi ini umumnya tidak disarankan karena kinerja yang lambat

Jika Anda tidak mencari dukungan pemrosesan paralel, implementasi yang ditawarkan oleh

>>> import collections
>>> d = collections.OrderedDict(one=1, two=2, three=3)

>>> d
OrderedDict([('one', 1), ('two', 2), ('three', 3)])

>>> d["four"] = 4
>>> d
OrderedDict([('one', 1), ('two', 2),
             ('three', 3), ('four', 4)])

>>> d.keys()
odict_keys(['one', 'two', 'three', 'four'])
85 adalah pilihan default yang sangat baik untuk mengimplementasikan struktur data antrean FIFO di Python. Ini memberikan karakteristik kinerja yang Anda harapkan dari penerapan antrean yang baik dan juga dapat digunakan sebagai tumpukan (antrian LIFO)

Antrian Prioritas

A adalah struktur data wadah yang mengelola kumpulan catatan dengan kunci yang diurutkan secara total untuk menyediakan akses cepat ke catatan dengan kunci terkecil atau terbesar di kumpulan

Anda dapat menganggap antrean prioritas sebagai antrean yang dimodifikasi. Alih-alih mengambil elemen berikutnya dengan waktu penyisipan, ia mengambil elemen dengan prioritas tertinggi. Prioritas masing-masing elemen ditentukan oleh urutan yang diterapkan pada kuncinya

Antrian prioritas biasanya digunakan untuk menangani masalah penjadwalan. Misalnya, Anda mungkin menggunakannya untuk mengutamakan tugas dengan urgensi yang lebih tinggi

Pikirkan tentang pekerjaan penjadwal tugas sistem operasi

Idealnya, tugas dengan prioritas lebih tinggi pada sistem (seperti bermain game waktu nyata) harus didahulukan daripada tugas dengan prioritas lebih rendah (seperti mengunduh pembaruan di latar belakang). Dengan mengatur tugas yang tertunda dalam antrean prioritas yang menggunakan urgensi tugas sebagai kuncinya, penjadwal tugas dapat dengan cepat memilih tugas dengan prioritas tertinggi dan mengizinkannya untuk dijalankan terlebih dahulu

Di bagian ini, Anda akan melihat beberapa opsi bagaimana Anda dapat mengimplementasikan antrian prioritas di Python menggunakan struktur data bawaan atau struktur data yang termasuk dalam pustaka standar Python. Setiap implementasi akan memiliki kelebihan dan kekurangannya sendiri, tetapi menurut saya ada pemenang yang jelas untuk skenario yang paling umum. Mari kita cari tahu yang mana itu

>>> from collections import ChainMap >>> dict1 = {"one": 1, "two": 2} >>> dict2 = {"three": 3, "four": 4} >>> chain = ChainMap(dict1, dict2) >>> chain ChainMap({'one': 1, 'two': 2}, {'three': 3, 'four': 4}) >>> # ChainMap searches each collection in the chain >>> # from left to right until it finds the key (or fails): >>> chain["three"] 3 >>> chain["one"] 1 >>> chain["missing"] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'missing' _6. Antrean yang Diurutkan Secara Manual

Anda dapat menggunakan

>>> from collections import ChainMap
>>> dict1 = {"one": 1, "two": 2}
>>> dict2 = {"three": 3, "four": 4}
>>> chain = ChainMap(dict1, dict2)

>>> chain
ChainMap({'one': 1, 'two': 2}, {'three': 3, 'four': 4})

>>> # ChainMap searches each collection in the chain
>>> # from left to right until it finds the key (or fails):
>>> chain["three"]
3
>>> chain["one"]
1
>>> chain["missing"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'missing'
6 yang diurutkan untuk mengidentifikasi dan menghapus elemen terkecil atau terbesar dengan cepat. Kelemahannya adalah memasukkan elemen baru ke dalam daftar adalah operasi O(n) yang lambat

Sementara titik penyisipan dapat ditemukan dalam waktu O(log n) menggunakan perpustakaan standar, ini selalu didominasi oleh langkah penyisipan yang lambat

Mempertahankan urutan dengan menambahkan ke daftar dan menyortir ulang juga membutuhkan setidaknya O(n log n) waktu. Kelemahan lainnya adalah Anda harus secara manual mengatur ulang daftar ketika elemen baru dimasukkan. Sangat mudah untuk memperkenalkan bug dengan melewatkan langkah ini, dan beban selalu ada pada Anda, sang pengembang

Ini berarti daftar yang diurutkan hanya cocok sebagai antrian prioritas ketika hanya ada sedikit penyisipan

>>>

>>> from collections import ChainMap
>>> dict1 = {"one": 1, "two": 2}
>>> dict2 = {"three": 3, "four": 4}
>>> chain = ChainMap(dict1, dict2)

>>> chain
ChainMap({'one': 1, 'two': 2}, {'three': 3, 'four': 4})

>>> # ChainMap searches each collection in the chain
>>> # from left to right until it finds the key (or fails):
>>> chain["three"]
3
>>> chain["one"]
1
>>> chain["missing"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'missing'
3

>>> from collections import defaultdict >>> dd = defaultdict(list) >>> # Accessing a missing key creates it and >>> # initializes it using the default factory, >>> # i.e. list() in this example: >>> dd["dogs"].append("Rufus") >>> dd["dogs"].append("Kathrin") >>> dd["dogs"].append("Mr Sniffles") >>> dd["dogs"] ['Rufus', 'Kathrin', 'Mr Sniffles'] _25. Tumpukan Biner Berbasis Daftar

>>> from collections import defaultdict
>>> dd = defaultdict(list)

>>> # Accessing a missing key creates it and
>>> # initializes it using the default factory,
>>> # i.e. list() in this example:
>>> dd["dogs"].append("Rufus")
>>> dd["dogs"].append("Kathrin")
>>> dd["dogs"].append("Mr Sniffles")

>>> dd["dogs"]
['Rufus', 'Kathrin', 'Mr Sniffles']
25 adalah implementasi tumpukan biner yang biasanya didukung oleh
>>> from collections import ChainMap
>>> dict1 = {"one": 1, "two": 2}
>>> dict2 = {"three": 3, "four": 4}
>>> chain = ChainMap(dict1, dict2)

>>> chain
ChainMap({'one': 1, 'two': 2}, {'three': 3, 'four': 4})

>>> # ChainMap searches each collection in the chain
>>> # from left to right until it finds the key (or fails):
>>> chain["three"]
3
>>> chain["one"]
1
>>> chain["missing"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'missing'
6 biasa, dan mendukung penyisipan dan ekstraksi elemen terkecil dalam waktu O(log n)

Modul ini adalah pilihan yang baik untuk mengimplementasikan antrian prioritas dengan Python. Karena

>>> from collections import defaultdict
>>> dd = defaultdict(list)

>>> # Accessing a missing key creates it and
>>> # initializes it using the default factory,
>>> # i.e. list() in this example:
>>> dd["dogs"].append("Rufus")
>>> dd["dogs"].append("Kathrin")
>>> dd["dogs"].append("Mr Sniffles")

>>> dd["dogs"]
['Rufus', 'Kathrin', 'Mr Sniffles']
_25 secara teknis hanya menyediakan implementasi min-heap, untuk memastikan stabilitas penyortiran dan fitur lain yang biasanya diharapkan dari antrean prioritas praktis

>>>

>>> from collections import ChainMap
>>> dict1 = {"one": 1, "two": 2}
>>> dict2 = {"three": 3, "four": 4}
>>> chain = ChainMap(dict1, dict2)

>>> chain
ChainMap({'one': 1, 'two': 2}, {'three': 3, 'four': 4})

>>> # ChainMap searches each collection in the chain
>>> # from left to right until it finds the key (or fails):
>>> chain["three"]
3
>>> chain["one"]
1
>>> chain["missing"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'missing'
4

>>> from collections import defaultdict >>> dd = defaultdict(list) >>> # Accessing a missing key creates it and >>> # initializes it using the default factory, >>> # i.e. list() in this example: >>> dd["dogs"].append("Rufus") >>> dd["dogs"].append("Kathrin") >>> dd["dogs"].append("Mr Sniffles") >>> dd["dogs"] ['Rufus', 'Kathrin', 'Mr Sniffles'] 29. Antrian Prioritas yang Indah

menggunakan

>>> from collections import defaultdict
>>> dd = defaultdict(list)

>>> # Accessing a missing key creates it and
>>> # initializes it using the default factory,
>>> # i.e. list() in this example:
>>> dd["dogs"].append("Rufus")
>>> dd["dogs"].append("Kathrin")
>>> dd["dogs"].append("Mr Sniffles")

>>> dd["dogs"]
['Rufus', 'Kathrin', 'Mr Sniffles']
_25 secara internal dan berbagi kompleksitas ruang dan waktu yang sama. Perbedaannya adalah bahwa
>>> from collections import defaultdict
>>> dd = defaultdict(list)

>>> # Accessing a missing key creates it and
>>> # initializes it using the default factory,
>>> # i.e. list() in this example:
>>> dd["dogs"].append("Rufus")
>>> dd["dogs"].append("Kathrin")
>>> dd["dogs"].append("Mr Sniffles")

>>> dd["dogs"]
['Rufus', 'Kathrin', 'Mr Sniffles']
_32 disinkronkan dan menyediakan semantik penguncian untuk mendukung banyak produsen dan konsumen secara bersamaan

Bergantung pada kasus penggunaan Anda, ini mungkin membantu, atau mungkin hanya memperlambat program Anda sedikit. Bagaimanapun, Anda mungkin lebih suka antarmuka berbasis kelas yang disediakan oleh

>>> from collections import defaultdict
>>> dd = defaultdict(list)

>>> # Accessing a missing key creates it and
>>> # initializes it using the default factory,
>>> # i.e. list() in this example:
>>> dd["dogs"].append("Rufus")
>>> dd["dogs"].append("Kathrin")
>>> dd["dogs"].append("Mr Sniffles")

>>> dd["dogs"]
['Rufus', 'Kathrin', 'Mr Sniffles']
32 daripada antarmuka berbasis fungsi yang disediakan oleh
>>> from collections import defaultdict
>>> dd = defaultdict(list)

>>> # Accessing a missing key creates it and
>>> # initializes it using the default factory,
>>> # i.e. list() in this example:
>>> dd["dogs"].append("Rufus")
>>> dd["dogs"].append("Kathrin")
>>> dd["dogs"].append("Mr Sniffles")

>>> dd["dogs"]
['Rufus', 'Kathrin', 'Mr Sniffles']
25

>>>

>>> from collections import ChainMap
>>> dict1 = {"one": 1, "two": 2}
>>> dict2 = {"three": 3, "four": 4}
>>> chain = ChainMap(dict1, dict2)

>>> chain
ChainMap({'one': 1, 'two': 2}, {'three': 3, 'four': 4})

>>> # ChainMap searches each collection in the chain
>>> # from left to right until it finds the key (or fails):
>>> chain["three"]
3
>>> chain["one"]
1
>>> chain["missing"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'missing'
5

Antrian Prioritas dengan Python. Ringkasan

Python menyertakan beberapa implementasi antrean prioritas yang siap untuk Anda gunakan

>>> from collections import defaultdict
>>> dd = defaultdict(list)

>>> # Accessing a missing key creates it and
>>> # initializes it using the default factory,
>>> # i.e. list() in this example:
>>> dd["dogs"].append("Rufus")
>>> dd["dogs"].append("Kathrin")
>>> dd["dogs"].append("Mr Sniffles")

>>> dd["dogs"]
['Rufus', 'Kathrin', 'Mr Sniffles']
29 menonjol dari paket dengan antarmuka berorientasi objek yang bagus dan nama yang dengan jelas menyatakan maksudnya. Ini harus menjadi pilihan pilihan Anda

Jika Anda ingin menghindari penguncian

>>> from collections import defaultdict
>>> dd = defaultdict(list)

>>> # Accessing a missing key creates it and
>>> # initializes it using the default factory,
>>> # i.e. list() in this example:
>>> dd["dogs"].append("Rufus")
>>> dd["dogs"].append("Kathrin")
>>> dd["dogs"].append("Mr Sniffles")

>>> dd["dogs"]
['Rufus', 'Kathrin', 'Mr Sniffles']
29, maka menggunakan modul
>>> from collections import defaultdict
>>> dd = defaultdict(list)

>>> # Accessing a missing key creates it and
>>> # initializes it using the default factory,
>>> # i.e. list() in this example:
>>> dd["dogs"].append("Rufus")
>>> dd["dogs"].append("Kathrin")
>>> dd["dogs"].append("Mr Sniffles")

>>> dd["dogs"]
['Rufus', 'Kathrin', 'Mr Sniffles']
25 secara langsung juga merupakan pilihan yang baik

Kesimpulan. Struktur Data Python

Itu menyimpulkan tur Anda tentang struktur data umum dengan Python. Dengan pengetahuan yang Anda peroleh di sini, Anda siap menerapkan struktur data efisien yang tepat untuk algoritme atau kasus penggunaan khusus Anda

Dalam tutorial ini, Anda telah belajar

  • Tipe data abstrak umum mana yang dibangun ke dalam pustaka standar Python
  • Bagaimana tipe data abstrak yang paling umum dipetakan ke skema penamaan Python
  • Cara menempatkan tipe data abstrak untuk penggunaan praktis dalam berbagai algoritme

Jika Anda menikmati apa yang Anda pelajari dalam contoh ini dari Trik Python, maka pastikan untuk membaca sisa buku ini

Jika Anda tertarik untuk meningkatkan pengetahuan struktur data umum Anda, maka saya sangat merekomendasikan Steven S. Manual Desain Algoritma Skiena. Ini memberikan keseimbangan besar antara mengajari Anda struktur data dasar (dan lebih lanjut) dan menunjukkan kepada Anda cara menerapkannya dalam kode Anda. Buku Steve sangat membantu dalam penulisan tutorial ini

Tandai sebagai Selesai

Tonton Sekarang Tutorial ini memiliki kursus video terkait yang dibuat oleh tim Real Python. Tonton bersama dengan tutorial tertulis untuk memperdalam pemahaman Anda. Tumpukan dan Antrian. Memilih Struktur Data Ideal

🐍 Trik Python 💌

Dapatkan Trik Python singkat & manis yang dikirim ke kotak masuk Anda setiap beberapa hari. Tidak pernah ada spam. Berhenti berlangganan kapan saja. Dikuratori oleh tim Real Python

Struktur data dan implementasi algoritma dalam python

Kirimi Saya Trik Python »

Tentang Dan Bader

Struktur data dan implementasi algoritma dalam python
Struktur data dan implementasi algoritma dalam python

Dan Bader adalah pemilik dan pemimpin redaksi Real Python dan pengembang utama realpython. platform pembelajaran com. Dan telah menulis kode selama lebih dari 20 tahun dan memegang gelar master dalam ilmu komputer

» Lebih lanjut tentang Dan


Setiap tutorial di Real Python dibuat oleh tim pengembang sehingga memenuhi standar kualitas tinggi kami. Anggota tim yang mengerjakan tutorial ini adalah

Struktur data dan implementasi algoritma dalam python

Aldren

Struktur data dan implementasi algoritma dalam python

Daud

Struktur data dan implementasi algoritma dalam python

Joanna

Struktur data dan implementasi algoritma dalam python

Yakub

Master Keterampilan Python Dunia Nyata Dengan Akses Tanpa Batas ke Python Nyata

Bergabunglah dengan kami dan dapatkan akses ke ribuan tutorial, kursus video langsung, dan komunitas pakar Pythonista

Tingkatkan Keterampilan Python Anda »

Guru Keterampilan Python Dunia Nyata
Dengan Akses Tak Terbatas ke Real Python

Bergabunglah dengan kami dan dapatkan akses ke ribuan tutorial, kursus video langsung, dan komunitas ahli Pythonista

Tingkatkan Keterampilan Python Anda »

Bagaimana menurut anda?

Nilai artikel ini

Tweet Bagikan Bagikan Email

Apa takeaway # 1 Anda atau hal favorit yang Anda pelajari?

Kiat Berkomentar. Komentar yang paling berguna adalah yang ditulis dengan tujuan belajar dari atau membantu siswa lain. dan dapatkan jawaban atas pertanyaan umum di portal dukungan kami

Bisakah saya mengimplementasikan struktur data dengan Python?

Python memungkinkan penggunanya untuk membuat Struktur Data mereka sendiri memungkinkan mereka untuk memiliki kontrol penuh atas fungsinya. Struktur Data yang paling menonjol adalah Stack, Queue, Tree, Linked List dan sebagainya yang juga tersedia untuk Anda dalam bahasa pemrograman lain.

Apakah Python bagus untuk struktur data dan algoritme?

Struktur Data adalah dasar dari setiap bahasa pemrograman di mana sebuah program dibangun. Python membantu mempelajari dasar-dasar struktur data ini dengan cara yang lebih sederhana dibandingkan dengan bahasa pemrograman lain .

Bagaimana Anda menerapkan algoritma dan struktur data?

Berikut adalah rencana langkah demi langkah untuk meningkatkan keterampilan struktur data dan algoritme Anda. .
Langkah 1. Memahami Kedalaman vs. .
Langkah 2. Mulai Pendekatan Kedalaman-Pertama—buat daftar pertanyaan inti. .
Langkah 3. Kuasai setiap struktur data. .
Langkah 4. Pengulangan Berjarak. .
Langkah 5. Isolasi teknik yang digunakan kembali. .
Langkah 6. Sekarang, waktunya untuk Breadth