面向物件Python - 資料結構



從語法的角度來看,Python資料結構非常直觀,並且提供了大量的操作選擇。你需要根據資料的構成、是否需要修改、是否是固定資料以及所需的訪問型別(例如開頭/結尾/隨機等)來選擇Python資料結構。

列表

列表代表Python中最通用的資料結構型別。列表是一個容器,它在方括號之間儲存用逗號分隔的值(專案或元素)。當我們想要處理多個相關值時,列表非常有用。由於列表將資料放在一起,我們可以同時對多個值執行相同的方法和操作。列表索引從零開始,與字串不同,列表是可變的。

資料結構 - 列表

>>>
>>> # Any Empty List
>>> empty_list = []
>>>
>>> # A list of String
>>> str_list = ['Life', 'Is', 'Beautiful']
>>> # A list of Integers
>>> int_list = [1, 4, 5, 9, 18]
>>>
>>> #Mixed items list
>>> mixed_list = ['This', 9, 'is', 18, 45.9, 'a', 54, 'mixed', 99, 'list']
>>> # To print the list
>>>
>>> print(empty_list)
[]
>>> print(str_list)
['Life', 'Is', 'Beautiful']
>>> print(type(str_list))
<class 'list'>
>>> print(int_list)
[1, 4, 5, 9, 18]
>>> print(mixed_list)
['This', 9, 'is', 18, 45.9, 'a', 54, 'mixed', 99, 'list']

訪問Python列表中的專案

列表的每個專案都分配一個數字——這就是該數字的索引或位置。索引總是從零開始,第二個索引是一,以此類推。要訪問列表中的專案,我們可以在方括號內使用這些索引號。例如,觀察以下程式碼:

>>> mixed_list = ['This', 9, 'is', 18, 45.9, 'a', 54, 'mixed', 99, 'list']
>>>
>>> # To access the First Item of the list
>>> mixed_list[0]
'This'
>>> # To access the 4th item
>>> mixed_list[3]
18
>>> # To access the last item of the list
>>> mixed_list[-1]
'list'

空物件

空物件是最簡單和最基本的Python內建型別。我們多次在沒有注意到的情況下使用了它們,並且將其擴充套件到我們建立的每個類。編寫空類的主要目的是暫時阻止某些東西,稍後再擴充套件並新增行為。

向類新增行為意味著用物件替換資料結構並更改對它的所有引用。因此,在建立任何內容之前,檢查資料是否偽裝成物件非常重要。觀察以下程式碼以更好地理解

>>> #Empty objects
>>>
>>> obj = object()
>>> obj.x = 9
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
obj.x = 9
AttributeError: 'object' object has no attribute 'x'

因此,從上面可以看出,不可能直接在例項化的物件上設定任何屬性。當Python允許物件具有任意屬性時,它需要一定的系統記憶體來跟蹤每個物件具有哪些屬性,用於儲存屬性名稱及其值。即使沒有儲存屬性,也會為潛在的新屬性分配一定量的記憶體。

因此,預設情況下,Python停用了物件和一些其他內建物件的任意屬性。

>>> # Empty Objects
>>>
>>> class EmpObject:
    pass
>>> obj = EmpObject()
>>> obj.x = 'Hello, World!'
>>> obj.x
'Hello, World!'

因此,如果我們想要將屬性組合在一起,我們可以像上面程式碼中顯示的那樣將它們儲存在空物件中。但是,這種方法並不總是建議的。請記住,只有當您想要同時指定資料和行為時,才應該使用類和物件。

元組

元組類似於列表,可以儲存元素。但是,它們是不可變的,因此我們不能新增、刪除或替換物件。元組由於其不可變性而提供的最主要好處是,我們可以將它們用作字典中的鍵,或在物件需要雜湊值的其他位置。

元組用於儲存資料,而不是行為。如果您需要行為來操作元組,則需要將元組傳遞給執行該操作的函式(或另一個物件上的方法)。

由於元組可以充當字典鍵,因此儲存的值彼此不同。我們可以透過逗號分隔值來建立一個元組。元組用括號括起來,但不是強制性的。以下程式碼顯示了兩個相同的賦值。

>>> stock1 = 'MSFT', 95.00, 97.45, 92.45
>>> stock2 = ('MSFT', 95.00, 97.45, 92.45)
>>> type (stock1)
<class 'tuple'>
>>> type(stock2)
<class 'tuple'>
>>> stock1 == stock2
True
>>>

定義元組

元組與列表非常相似,只是所有元素都用括號括起來,而不是方括號。

就像切片列表一樣,您會得到一個新列表,而當您切片元組時,您會得到一個新的元組。

>>> tupl = ('Tuple','is', 'an','IMMUTABLE', 'list')
>>> tupl
('Tuple', 'is', 'an', 'IMMUTABLE', 'list')
>>> tupl[0]
'Tuple'
>>> tupl[-1]
'list'
>>> tupl[1:3]
('is', 'an')

Python元組方法

以下程式碼顯示了Python元組中的方法:

>>> tupl
('Tuple', 'is', 'an', 'IMMUTABLE', 'list')
>>> tupl.append('new')
Traceback (most recent call last):
   File "<pyshell#148>", line 1, in <module>
      tupl.append('new')
AttributeError: 'tuple' object has no attribute 'append'
>>> tupl.remove('is')
Traceback (most recent call last):
   File "<pyshell#149>", line 1, in <module>
      tupl.remove('is')
AttributeError: 'tuple' object has no attribute 'remove'
>>> tupl.index('list')
4
>>> tupl.index('new')
Traceback (most recent call last):
   File "<pyshell#151>", line 1, in <module>
      tupl.index('new')
ValueError: tuple.index(x): x not in tuple
>>> "is" in tupl
True
>>> tupl.count('is')
1

從上面顯示的程式碼中,我們可以理解元組是不可變的,因此:

  • 不能向元組新增元素。

  • 不能追加或擴充套件方法。

  • 不能從元組中刪除元素。

  • 元組沒有remove或pop方法。

  • 元組中可用的方法是count和index。

字典

字典是Python的內建資料型別之一,它定義了鍵和值之間的一對一關係。

定義字典

觀察以下程式碼以瞭解如何定義字典:

>>> # empty dictionary
>>> my_dict = {}
>>>
>>> # dictionary with integer keys
>>> my_dict = { 1:'msft', 2: 'IT'}
>>>
>>> # dictionary with mixed keys
>>> my_dict = {'name': 'Aarav', 1: [ 2, 4, 10]}
>>>
>>> # using built-in function dict()
>>> my_dict = dict({1:'msft', 2:'IT'})
>>>
>>> # From sequence having each item as a pair
>>> my_dict = dict([(1,'msft'), (2,'IT')])
>>>
>>> # Accessing elements of a dictionary
>>> my_dict[1]
'msft'
>>> my_dict[2]
'IT'
>>> my_dict['IT']
Traceback (most recent call last):
   File "<pyshell#177>", line 1, in <module>
   my_dict['IT']
KeyError: 'IT'
>>>

從上面的程式碼中我們可以觀察到

  • 首先,我們建立一個包含兩個元素的字典,並將其賦值給變數my_dict。每個元素都是一個鍵值對,所有元素都用花括號括起來。

  • 數字1是鍵,msft是其值。類似地,2是鍵,IT是其值。

  • 您可以透過鍵獲取值,但反之則不行。因此,當我們嘗試my_dict[‘IT’]時,它會引發異常,因為IT不是鍵。

修改字典

觀察以下程式碼以瞭解如何修改字典:

>>> # Modifying a Dictionary
>>>
>>> my_dict
{1: 'msft', 2: 'IT'}
>>> my_dict[2] = 'Software'
>>> my_dict
{1: 'msft', 2: 'Software'}
>>>
>>> my_dict[3] = 'Microsoft Technologies'
>>> my_dict
{1: 'msft', 2: 'Software', 3: 'Microsoft Technologies'}

從上面的程式碼中我們可以觀察到:

  • 字典中不能有重複的鍵。更改現有鍵的值將刪除舊值。

  • 您可以隨時新增新的鍵值對。

  • 字典在元素之間沒有順序的概念。它們是簡單的無序集合。

在字典中混合資料型別

觀察以下程式碼以瞭解如何在字典中混合資料型別:

>>> # Mixing Data Types in a Dictionary
>>>
>>> my_dict
{1: 'msft', 2: 'Software', 3: 'Microsoft Technologies'}
>>> my_dict[4] = 'Operating System'
>>> my_dict
{1: 'msft', 2: 'Software', 3: 'Microsoft Technologies', 4: 'Operating System'}
>>> my_dict['Bill Gates'] = 'Owner'
>>> my_dict
{1: 'msft', 2: 'Software', 3: 'Microsoft Technologies', 4: 'Operating System',
'Bill Gates': 'Owner'}

從上面的程式碼中我們可以觀察到:

  • 不僅是字串,字典值可以是任何資料型別,包括字串、整數,甚至字典本身。

  • 與字典值不同,字典鍵受到更多限制,但可以是任何型別,例如字串、整數或其他任何型別。

從字典中刪除專案

觀察以下程式碼以瞭解如何從字典中刪除專案:

>>> # Deleting Items from a Dictionary
>>>
>>> my_dict
{1: 'msft', 2: 'Software', 3: 'Microsoft Technologies', 4: 'Operating System',
'Bill Gates': 'Owner'}
>>>
>>> del my_dict['Bill Gates']
>>> my_dict
{1: 'msft', 2: 'Software', 3: 'Microsoft Technologies', 4: 'Operating System'}
>>>
>>> my_dict.clear()
>>> my_dict
{}

從上面的程式碼中我們可以觀察到:

  • del - 允許您按鍵從字典中刪除單個專案。

  • clear - 從字典中刪除所有專案。

集合

Set() 是一個無序集合,沒有重複元素。雖然單個專案是不可變的,但集合本身是可變的,也就是說我們可以向集合中新增或刪除元素/專案。我們可以對集合執行並集、交集等數學運算。

雖然集合通常可以使用樹來實現,但Python中的集合可以使用雜湊表來實現。這為它提供了一種高度最佳化的檢查特定元素是否包含在集合中的方法。

建立集合

集合是透過將所有專案(元素)放在花括號{}內,用逗號分隔,或者使用內建函式set()來建立的。觀察以下程式碼行:

>>> #set of integers
>>> my_set = {1,2,4,8}
>>> print(my_set)
{8, 1, 2, 4}
>>>
>>> #set of mixed datatypes
>>> my_set = {1.0, "Hello World!", (2, 4, 6)}
>>> print(my_set)
{1.0, (2, 4, 6), 'Hello World!'}
>>>

集合的方法

觀察以下程式碼以瞭解集合的方法:

>>> >>> #METHODS FOR SETS
>>>
>>> #add(x) Method
>>> topics = {'Python', 'Java', 'C#'}
>>> topics.add('C++')
>>> topics
{'C#', 'C++', 'Java', 'Python'}
>>>
>>> #union(s) Method, returns a union of two set.
>>> topics
{'C#', 'C++', 'Java', 'Python'}
>>> team = {'Developer', 'Content Writer', 'Editor','Tester'}
>>> group = topics.union(team)
>>> group
{'Tester', 'C#', 'Python', 'Editor', 'Developer', 'C++', 'Java', 'Content
Writer'}
>>> # intersets(s) method, returns an intersection of two sets
>>> inters = topics.intersection(team)
>>> inters
set()
>>>
>>> # difference(s) Method, returns a set containing all the elements of
invoking set but not of the second set.
>>>
>>> safe = topics.difference(team)
>>> safe
{'Python', 'C++', 'Java', 'C#'}
>>>
>>> diff = topics.difference(group)
>>> diff
set()
>>> #clear() Method, Empties the whole set.
>>> group.clear()
>>> group
set()
>>>

集合的運算子

觀察以下程式碼以瞭解集合的運算子:

>>> # PYTHON SET OPERATIONS
>>>
>>> #Creating two sets
>>> set1 = set()
>>> set2 = set()
>>>
>>> # Adding elements to set
>>> for i in range(1,5):
   set1.add(i)
>>> for j in range(4,9):
   set2.add(j)
>>> set1
{1, 2, 3, 4}
>>> set2
{4, 5, 6, 7, 8}
>>>
>>> #Union of set1 and set2
>>> set3 = set1 | set2 # same as set1.union(set2)
>>> print('Union of set1 & set2: set3 = ', set3)
Union of set1 & set2: set3 = {1, 2, 3, 4, 5, 6, 7, 8}
>>>
>>> #Intersection of set1 & set2
>>> set4 = set1 & set2 # same as set1.intersection(set2)
>>> print('Intersection of set1 and set2: set4 = ', set4)
Intersection of set1 and set2: set4 = {4}
>>>
>>> # Checking relation between set3 and set4
>>> if set3 > set4: # set3.issuperset(set4)
   print('Set3 is superset of set4')
elif set3 < set4: #set3.issubset(set4)
   print('Set3 is subset of set4')
else: #set3 == set4
   print('Set 3 is same as set4')
Set3 is superset of set4
>>>
>>> # Difference between set3 and set4
>>> set5 = set3 - set4
>>> print('Elements in set3 and not in set4: set5 = ', set5)
Elements in set3 and not in set4: set5 = {1, 2, 3, 5, 6, 7, 8}
>>>
>>> # Check if set4 and set5 are disjoint sets
>>> if set4.isdisjoint(set5):
   print('Set4 and set5 have nothing in common\n')
Set4 and set5 have nothing in common
>>> # Removing all the values of set5
>>> set5.clear()
>>> set5 set()
廣告
© . All rights reserved.