資料結構


從語法的角度來看,Python資料結構非常直觀,它們提供了大量操作選擇。 您需要根據資料所涉及的內容,是否需要修改,或者它是否為固定資料以及需要什麼存取型別(如開始/結束/隨機等)來選擇Python資料結構。

列表(List)

列表(List)代表了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

從上面顯示的程式碼中,我們可以知道元組是不可變的,因此 -

  • 不能將元素新增到元組中。
  • 不能附加或擴充套件一個方法。
  • 不能從元組中移除元素。
  • 元組沒有刪除或彈出方法。
  • 計數和索引是元組中可用的方法。

字典

Dictionary是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()