《Python 簡明教程》讀書筆記系列四 —— 資料結構

yidajiabei發表於2020-04-19

資料結構基本上是這樣的 - 它們是能夠將一些資料組合在一起的一種結構。換句話說,它們是被用來儲存相關資料的集合。

Python 中有四種內建的資料結構 - list, tuple, dictionary and set 。我們將看到如何使用它們以及它們如何使我們的生活變得更簡潔。

List

list 是一種儲存有序項集合的資料結構。也就是說,你可以在列表中儲存一系列項。在 Python 中你使用逗號隔開它們。

專案列表應該使用方括號括起來,以便 Python 能夠理解你正在定義一個列表。一旦建立了列表,你就可以在列表中增加、刪除或者搜尋列表中的項。正因為我們可以增加和刪除項,所以我們稱列表是一種 可變 資料型別,也就是說這個型別可以被改變。

物件和類的簡介

列表是使用物件和類的一個例子。當我們使用一個變數 i 併為它賦值時,例如將整數 5 賦給它。我們可以將其看作是建立一個 物件 i (即,例項)的過程,它對應的 (即,型別)為 int 。實際上,你可以通過檢視 help(int) 來更好地理解這一點。

一個類也可以有 方法 ,即只能被該類呼叫的函式。只有當你擁有該類的物件時,才能使用這些函式。例如,Python 為 列表 類提供了一個 append 函式,它允許你在列表的末尾新增一個元素(或者項)。

一個類也可以有 欄位 ,它們只是為該類定義的變數。只有當你擁有該類的物件時,才可以使用這些變數 / 名稱。欄位也可以用點訪問。

示例:

# 這是我的讀書清單
booklist = ['b', 'a', 'c']

print('I have', len(booklist), 'books to read.')

print('These books are:', end=' ')
for book in booklist:
    print(book, end=' ')

print('\nI also have d to read.')
booklist.append('d')
print('My booklist list is now', booklist)

print('I will sort my list now')
booklist.sort()
print('Sorted booklist is', booklist)

print('The first book I will read is', booklist[0])
oldbook = booklist[0]
del booklist[0]
print('I read the', oldbook)
print('My booklist is now', booklist)

輸出為:

I have 3 books to read.
These books are: b a c 
I also have d to read.
My booklist list is now ['b', 'a', 'c', 'd']
I will sort my list now
Sorted booklist is ['a', 'b', 'c', 'd']
The first book I will read is a
I read the a
My booklist is now ['b', 'c', 'd']

元組

元組用於將多個物件組合在一起。可以將它們近似看作列表,但是沒有列表類提供的許多功能。元組的一個重要特徵是,它們和字串一樣是 不可變 的,即你不能修改元組。

元組是由一些特殊的項定義的,這些項在一對可選的圓括號中,由逗號隔開。

元組通常用於語句或者使用者自定義的函式可以安全地認為值的集合(即,值的元組)不會改變的情況。

例子:

# 儘管圓括號是可選的,
# 我還是建議使用圓括號,
# 來表示元組的開始和結束。
# 因為顯式總比隱式更好。
house = ('I', 'You', 'He')
print('Number of people in the house is', len(house))

new_house = 'Her', house # parentheses(圓括號) not required but are a good idea
print('Number of beds in the new house is', len(new_house)-1+len(new_house[1]))
print('All people in new house are', new_house)
print('People brought from old house are', new_house[1])
print('Last person brought from old house is', new_house[1][2])
print('Number of people in the new house is',
      len(new_house)-1+len(new_house[1]))

輸出為:

Number of people in the house is 3
Number of beds in the new house is 4
All people in new house are ('Her', ('I', 'You', 'He'))
People brought from old house are ('I', 'You', 'He')
Last person brought from old house is He
Number of people in the new house is 4

字典

我們將 相關聯。注意,鍵必須是唯一的!

注意,對於字典的鍵,你只能使用不可變物件(比如字串),但是對於字典的值,不可變物件或者可變物件都可以使用。這基本上就意味著,對於字典的鍵,你最好只使用簡單點的物件。

我們通過 d = {key1 : value1, key2 : value2 },就可以指定字典中的鍵值對。注意,一個鍵值對中的鍵與值由冒號隔開,而不同鍵值對之間是由逗號隔開,所有的鍵值對以及冒號、逗號都包含在一對花括號中。

記住,字典中的鍵值對不以任何方式排序(不像列表中的項一樣有從小到大遞增的索引)。如果你想要得到一個特殊的順序。那麼在使用字典之前,你必須自己對其進行排序。

你將要使用的字典是 dict 類的一個例項 / 物件。

示例:

# 'sg' 是 's'tudent'g'rades 的縮寫,意思是學生成績

sg = {
    'a': 59,
    'b': 61,
    'c': 65
}

print("a's grade is", sg['a'])

# 刪除一個鍵值對
del sg['c']

print('\nThere are {} students in the student-'
'grade\n'.format(len(sg)))

for name, grade in sg.items():
    print('Student {} at {}'.format(name, grade))

# 新增一個鍵值對
sg['d'] = 99

if 'd' in sg:
    print("\nd's grade is", sg['d'])

輸出為:

a's grade is 59

There are 2 students in the student-grade

Student a at 59
Student b at 61

d's grade is 99

未完待續

本作品採用《CC 協議》,轉載必須註明作者和本文連結

日拱一卒,功不唐捐

相關文章