資料結構

You don’t have to be an expert to correctly make a nested data structure. In Python, you have to be an idiot not to be able to do it, because you just write it down.

Peter Norvig

純量類型中我們已經知道 Python 的基本資料單位稱作純量(scalar),純量扮演的角色就像是樂高、積木、模型或拼圖等遊戲中的基本單元零件,透過結合基本資料單位,堆疊出更進階的 Python 應用。接下來我們會從純量(scalars)邁向結構(collections),認識 Python 基本的資料結構:

  • list
  • tuple
  • dict
  • set

使用 type() 函數回傳資料結構

我們不需要自己猜測物件屬於何種資料結構,而是採用與回傳純量類型相同的辦法,使用一個函數 type() 讓 Python 告訴我們答案為何。

player_list = ["Ron Harper", "Michael Jordan", "Scottie Pippen", "Dennis Rodman", "Luc Longley"]
player_tuple = tuple(player_list)
player_dict = {
    "PG": "Ron Harper",
    "SG": "Michael Jordan",
    "SF": "Scottie Pippen",
    "PF": "Dennis Rodman",
    "C": "Luc Longley"
}
player_set = set(player_list)

print(type(player_list))
print(type(player_tuple))
print(type(player_dict))
print(type(player_set))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
## <class 'list'>
## <class 'tuple'>
## <class 'dict'>
## <class 'set'>
1
2
3
4

list

list 是 Python 常用的資料結構,可以容納不同類型的純量與不同長度的資料結構,在建立的時候使用中括號 [] 將希望儲存的資訊包括起來。在 best_chicago_bulls 的 list 中我們儲存了 6 個資料內容,分別是三個文字記錄球季、隊名與總教練;一個長度為 2 的 list 記錄了勝場數與敗場數;一個長度為 5 的 list 記錄了先發的五位球員;一個布林記錄是否有獲得該球季的總冠軍。

season = "1995-1996"
team = "Chicago Bulls"
coach = "Phil Jackson"
records = [72, 10]
starting_lineup = ["Ron Harper", "Michael Jordan", "Scottie Pippen", "Dennis Rodman", "Luc Longley"]
won_championship = True

best_chicago_bulls = [season, team, coach, records, starting_lineup, won_championship]
print(type(best_chicago_bulls))
1
2
3
4
5
6
7
8
9
## <class 'list'>
1

有時候我們也可以使用 Python 的內建函數 list() 來創建,例如常被用作產生數列的內建函數 range() 的輸出不會被印出所有的數字,這時可以用轉換為 list 來觀察其中包含的數字。

int_seq = range(10)
print(int_seq)
int_list = list(int_seq)
print(int_list)
print(type(int_list))
1
2
3
4
5
## range(0, 10)
## [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
## <class 'list'>
1
2
3

如何操作 list

使用 list 來將多筆資料儲存於一個物件之中,像是在進行化零為整的工作,Python 必然也能夠讓我們進行逆向化整為零的子集(subsetting),有關於子集的操作技巧,又可細分為:

  • 索引(indexing)
  • 切割(slicing)

利用內建函數 len() 可以先暸解我們想要取為子集(subset)的 list 長度(儲存的資料個數)為何,進而利用索引、切割的技法。

season = "1995-1996"
team = "Chicago Bulls"
coach = "Phil Jackson"
records = [72, 10]
starting_lineup = ["Ron Harper", "Michael Jordan", "Scottie Pippen", "Dennis Rodman", "Luc Longley"]
won_championship = True

best_chicago_bulls = [season, team, coach, records, starting_lineup, won_championship]
print(len(best_chicago_bulls))
1
2
3
4
5
6
7
8
9
## 6
1
season = "1995-1996"
team = "Chicago Bulls"
coach = "Phil Jackson"
records = [72, 10]
starting_lineup = ["Ron Harper", "Michael Jordan", "Scottie Pippen", "Dennis Rodman", "Luc Longley"]
won_championship = True

best_chicago_bulls = [season, team, coach, records, starting_lineup, won_championship]
print(best_chicago_bulls[0])
print(best_chicago_bulls[1])
print(best_chicago_bulls[2])
print(best_chicago_bulls[3])
print(best_chicago_bulls[4])
print(best_chicago_bulls[5])
1
2
3
4
5
6
7
8
9
10
11
12
13
14
## 1995-1996
## Chicago Bulls
## Phil Jackson
## [72, 10]
## ['Ron Harper', 'Michael Jordan', 'Scottie Pippen', 'Dennis Rodman', 'Luc Longley']
## True
1
2
3
4
5
6

從右邊則由 -1 開始。

season = "1995-1996"
team = "Chicago Bulls"
coach = "Phil Jackson"
records = [72, 10]
starting_lineup = ["Ron Harper", "Michael Jordan", "Scottie Pippen", "Dennis Rodman", "Luc Longley"]
won_championship = True

best_chicago_bulls = [season, team, coach, records, starting_lineup, won_championship]
print(best_chicago_bulls[-1])
print(best_chicago_bulls[-2])
print(best_chicago_bulls[-3])
print(best_chicago_bulls[-4])
print(best_chicago_bulls[-5])
print(best_chicago_bulls[-6])
1
2
3
4
5
6
7
8
9
10
11
12
13
14
## True
## ['Ron Harper', 'Michael Jordan', 'Scottie Pippen', 'Dennis Rodman', 'Luc Longley']
## [72, 10]
## Phil Jackson
## Chicago Bulls
## 1995-1996
1
2
3
4
5
6

利用 [start:stop:step] 對 list 指定要切割出來的部分資料為何,其中 Python 慣例 stop 不會出現在最後選擇出來的結果中,例如我們希望將位於 [0][1][2] 的資料另外切割為一個長度為 3 的 list,要使用 [0:3] 而非 [0:2]

season = "1995-1996"
team = "Chicago Bulls"
coach = "Phil Jackson"
records = [72, 10]
starting_lineup = ["Ron Harper", "Michael Jordan", "Scottie Pippen", "Dennis Rodman", "Luc Longley"]
won_championship = True

best_chicago_bulls = [season, team, coach, records, starting_lineup, won_championship]
print(best_chicago_bulls[0:3])
1
2
3
4
5
6
7
8
9
## ['1995-1996', 'Chicago Bulls', 'Phil Jackson']
1

使用切割的技巧時, startstopstep 這三個參數都有預設值, start 預設是 0, stop 預設為 -1(即最末端的索引值 + 1), step 預設為 1,假如沒有指定就採預設值,像是切割出位於 [1][3][5] 這三個位置的資料可以簡單使用 [::2]

season = "1995-1996"
team = "Chicago Bulls"
coach = "Phil Jackson"
records = [72, 10]
starting_lineup = ["Ron Harper", "Michael Jordan", "Scottie Pippen", "Dennis Rodman", "Luc Longley"]
won_championship = True

best_chicago_bulls = [season, team, coach, records, starting_lineup, won_championship]
print(best_chicago_bulls[::2])
1
2
3
4
5
6
7
8
9
## ['1995-1996', 'Phil Jackson', ['Ron Harper', 'Michael Jordan', 'Scottie Pippen', 'Dennis Rodman', 'Luc Longley']]
1

比較特別的 step 參數如果指定為 -1 可以將 list 的資料順序顛倒。

season = "1995-1996"
team = "Chicago Bulls"
coach = "Phil Jackson"
records = [72, 10]
starting_lineup = ["Ron Harper", "Michael Jordan", "Scottie Pippen", "Dennis Rodman", "Luc Longley"]
won_championship = True

best_chicago_bulls = [season, team, coach, records, starting_lineup, won_championship]
print(best_chicago_bulls[::-1])
1
2
3
4
5
6
7
8
9
## [True, ['Ron Harper', 'Michael Jordan', 'Scottie Pippen', 'Dennis Rodman', 'Luc Longley'], [72, 10], 'Phil Jackson', 'Chicago Bulls', '1995-1996']
1

除了索引與切割,常用的 list 操作還有新增、刪除與排序資料,新增我們可以使用 list.append(x) 將 x 加入到 list 的末端;例如將 Toni Kukoc 加入至球員陣容之中。

season = "1995-1996"
team = "Chicago Bulls"
coach = "Phil Jackson"
records = [72, 10]
starting_lineup = ["Ron Harper", "Michael Jordan", "Scottie Pippen", "Dennis Rodman", "Luc Longley"]
won_championship = True

best_chicago_bulls = [season, team, coach, records, starting_lineup, won_championship]
best_chicago_bulls[4].append("Toni Kukoc")
print(best_chicago_bulls[4])
1
2
3
4
5
6
7
8
9
10
## ['Ron Harper', 'Michael Jordan', 'Scottie Pippen', 'Dennis Rodman', 'Luc Longley', 'Toni Kukoc']
1

或者使用 list.insert(index, x) 將 x 加入到 list 中指定的索引值位置。

season = "1995-1996"
team = "Chicago Bulls"
coach = "Phil Jackson"
records = [72, 10]
starting_lineup = ["Ron Harper", "Michael Jordan", "Scottie Pippen", "Dennis Rodman", "Luc Longley"]
won_championship = True

best_chicago_bulls = [season, team, coach, records, starting_lineup, won_championship]
best_chicago_bulls[4].insert(5, "Toni Kukoc")
print(best_chicago_bulls[4])
1
2
3
4
5
6
7
8
9
10
## ['Ron Harper', 'Michael Jordan', 'Scottie Pippen', 'Dennis Rodman', 'Luc Longley', 'Toni Kukoc']
1

刪除我們可以使用 list.pop() 將 list 最末端的資料拋出;例如將 Luc Longley 從先發陣容中拋出,用一個 center 物件接住。

season = "1995-1996"
team = "Chicago Bulls"
coach = "Phil Jackson"
records = [72, 10]
starting_lineup = ["Ron Harper", "Michael Jordan", "Scottie Pippen", "Dennis Rodman", "Luc Longley"]
won_championship = True

best_chicago_bulls = [season, team, coach, records, starting_lineup, won_championship]
center = best_chicago_bulls[4].pop()
print(center)
print(best_chicago_bulls[4])
1
2
3
4
5
6
7
8
9
10
11
## Luc Longley
## ['Ron Harper', 'Michael Jordan', 'Scottie Pippen', 'Dennis Rodman']
1
2

或者使用 del 將指定位置的資料刪除;例如將 Ron Harper 從先發陣容中移除。

season = "1995-1996"
team = "Chicago Bulls"
coach = "Phil Jackson"
records = [72, 10]
starting_lineup = ["Ron Harper", "Michael Jordan", "Scottie Pippen", "Dennis Rodman", "Luc Longley"]
won_championship = True

best_chicago_bulls = [season, team, coach, records, starting_lineup, won_championship]
del best_chicago_bulls[4][0]
print(best_chicago_bulls[4])
1
2
3
4
5
6
7
8
9
10
## ['Michael Jordan', 'Scottie Pippen', 'Dennis Rodman', 'Luc Longley']
1

排序我們可以使用 list.sort() 將 list 的資料預設以遞增排序,亦可以指定 list.sort(reverse=True) 以遞減排序。

season = "1995-1996"
team = "Chicago Bulls"
coach = "Phil Jackson"
records = [72, 10]
starting_lineup = ["Ron Harper", "Michael Jordan", "Scottie Pippen", "Dennis Rodman", "Luc Longley"]
won_championship = True

best_chicago_bulls = [season, team, coach, records, starting_lineup, won_championship]
# 數值遞增排序
best_chicago_bulls[3].sort()
print(best_chicago_bulls[3])
# 數值遞減排序
best_chicago_bulls[3].sort(reverse=True)
print(best_chicago_bulls[3])
# 文字遞增排序
best_chicago_bulls[4].sort()
print(best_chicago_bulls[4])
# 文字遞減排序
best_chicago_bulls[4].sort(reverse=True)
print(best_chicago_bulls[4])
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
## [10, 72]
## [72, 10]
## ['Dennis Rodman', 'Luc Longley', 'Michael Jordan', 'Ron Harper', 'Scottie Pippen']
## ['Scottie Pippen', 'Ron Harper', 'Michael Jordan', 'Luc Longley', 'Dennis Rodman']
1
2
3
4

tuple

tuple 是 Python 另一常用的資料結構,多數的特性都與 list 相同,在建立的時候使用小括號 () 將希望儲存的資訊包括起來。在 best_chicago_bulls 的 tuple 中我們儲存了 6 個資料內容,分別是三個文字記錄球季、隊名與總教練;一個長度為 2 的 list 記錄了勝場數與敗場數;一個長度為 5 的 list 記錄了先發的五位球員;一個布林記錄是否有獲得該球季的總冠軍。

season = "1995-1996"
team = "Chicago Bulls"
coach = "Phil Jackson"
records = [72, 10]
starting_lineup = ["Ron Harper", "Michael Jordan", "Scottie Pippen", "Dennis Rodman", "Luc Longley"]
won_championship = True

best_chicago_bulls = (season, team, coach, records, starting_lineup, won_championship)
print(best_chicago_bulls)
print(type(best_chicago_bulls))
1
2
3
4
5
6
7
8
9
10
## ('1995-1996', 'Chicago Bulls', 'Phil Jackson', [72, 10], ['Ron Harper', 'Michael Jordan', 'Scottie Pippen', 'Dennis Rodman', 'Luc Longley'], True)
## <class 'tuple'>
1
2

有時候我們也使用 Python 的內建函數 tuple() 來創建,例如常被用作產生數列的內建函數 range() 的輸出不會被印出所有的數字,這時可以用轉換為 tuple 來觀察其中包含的數字。

int_seq = range(10)
print(int_seq)
int_tuple = tuple(int_seq)
print(int_tuple)
print(type(int_tuple))
1
2
3
4
5
## range(0, 10)
## (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
## <class 'tuple'>
1
2
3

如何操作 tuple

tuple 在索引與切割與 list 部分完全相同。

season = "1995-1996"
team = "Chicago Bulls"
coach = "Phil Jackson"
records = [72, 10]
starting_lineup = ["Ron Harper", "Michael Jordan", "Scottie Pippen", "Dennis Rodman", "Luc Longley"]
won_championship = True

best_chicago_bulls = (season, team, coach, records, starting_lineup, won_championship)
# indexing
print(best_chicago_bulls[0])
print(best_chicago_bulls[-1])
# slicing
print(best_chicago_bulls[1:4])
print(best_chicago_bulls[::-1])
1
2
3
4
5
6
7
8
9
10
11
12
13
14
## 1995-1996
## True
## ('Chicago Bulls', 'Phil Jackson', [72, 10])
## (True, ['Ron Harper', 'Michael Jordan', 'Scottie Pippen', 'Dennis Rodman', 'Luc Longley'], [72, 10], 'Phil Jackson', 'Chicago Bulls', '1995-1996')
1
2
3
4

tuple 與 list 最大的差異在於 tuple 是不可變動(immutable)的資料結構,不具備任何包含新增、刪除與排序資料的操作。

season = "1995-1996"
team = "Chicago Bulls"
coach = "Phil Jackson"
records = [72, 10]
starting_lineup = ["Ron Harper", "Michael Jordan", "Scottie Pippen", "Dennis Rodman", "Luc Longley"]
won_championship = True
points_per_game = 105.2

best_chicago_bulls = (season, team, coach, records, starting_lineup, won_championship)
best_chicago_bulls.append(points_per_game)
1
2
3
4
5
6
7
8
9
10
## ---------------------------------------------------------------------------
## AttributeError                            Traceback (most recent call last)
## <ipython-input-22-ce0f5b442eea> in <module>()
##       8 
##       9 best_chicago_bulls = (season, team, coach, records, starting_lineup, won_championship)
## ---> 10 best_chicago_bulls.append(points_per_game)
## 
## AttributeError: 'tuple' object has no attribute 'append'
1
2
3
4
5
6
7
8

我們使用 Jupyter Notebook 的提示功能,tuple 可以使用的方法僅有 .count().index() 而這兩個方法也確實都不是能夠更動內容的函數。

tuple 可以使用的方法僅有 .count() 與 .index()

set

set 是 Python 較為少用的資料結構,在建立的時候使用大括號 {} 將希望儲存的資訊包括起來,set 只會儲存獨一的資料,若輸入了重複的資訊,則會只記錄一筆。在 positions 的 set 中我們儲存了 5 個文字,分別是兩個 "G" 、 兩個 "F" 與一個 "C" 記錄籃球場上的鋒衛位置,由於 set 的特性,這個物件的長度為 3。

positions = {"G", "G", "F", "F", "C"}
print(type(positions))
print(positions)
print(len(positions))
1
2
3
4
## <class 'set'>
## {'C', 'G', 'F'}
## 3
1
2
3

有時候我們也使用 Python 的內建函數 set() 來創建。

positions = ["G", "G", "F", "F", "C"]
print(positions)
print(len(positions))
print(type(positions))
positions = set(positions)
print(positions)
print(len(positions))
print(type(positions))
1
2
3
4
5
6
7
8
## ['G', 'G', 'F', 'F', 'C']
## 5
## <class 'list'>
## {'C', 'G', 'F'}
## 3
## <class 'set'>
1
2
3
4
5
6

如何操作 set

set 還有一點與其他資料結構很大的差異是,無法使用中括號 [] 做索引或切割。

positions = {"G", "G", "F", "F", "C"}
print(positions)
print(type(positions))
print(positions[0])
1
2
3
4
## {'C', 'G', 'F'}
## <class 'set'>
## ---------------------------------------------------------------------------
## TypeError                                 Traceback (most recent call last)
## <ipython-input-13-2e99bfc6a6fc> in <module>()
##       2 print(positions)
##       3 print(type(positions))
## ----> 4 print(positions[0])
## 
## TypeError: 'set' object does not support indexing
1
2
3
4
5
6
7
8
9
10

如果希望選取 set 中的資料,我們會在之後應用迴圈迭代來選取。

dict

dict 是 dictionary 的縮寫,這是一種與 list、tuple 及 set 截然不同的資料結構,這種資料結構除了儲存資料(values)以外,還另外利用標籤(keys)來對資料作索引,這樣的特性讓我們在選擇時可以使用資料的標籤,如此一來在面對長度很大的資料時,不需要耗時計算資料所在的位置,在建立的時候使用大括號 {} 將希望儲存的資訊包括起來,然後分別將資料與標籤以 keys 與 values 記錄。在 best_chicago_bulls 的 dict 中我們儲存了 7 個資料內容,分別是三個文字記錄球季、隊名與總教練;一個長度為 2 的 dict 記錄了勝場數與敗場數;一個長度為 5 的 dict 記錄了先發的五位球員;一個布林記錄是否有獲得該球季的總冠軍;最後是一個浮點數記錄場均得分。

season = "1995-1996"
team = "Chicago Bulls"
coach = "Phil Jackson"
records = {
    "wins": 72,
    "losses": 10
}
starting_lineup = {
    "PG": "Ron Harper",
    "SG": "Michael Jordan",
    "SF": "Scottie Pippen",
    "PF": "Dennis Rodman",
    "C": "Luc Longley"
}
won_championship = True
points_per_game = 105.2

best_chicago_bulls = {
    "season": season,
    "team": team,
    "coach": coach,
    "records": records,
    "startingLineup": starting_lineup,
    "wonChampionship": won_championship,
    "pointsPerGame": points_per_game
}
print(best_chicago_bulls)
print(type(best_chicago_bulls))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
## {'season': '1995-1996', 'team': 'Chicago Bulls', 'coach': 'Phil Jackson', 'records': {'wins': 72, 'losses': 10}, 'startingLineup': {'PG': 'Ron Harper', 'SG': 'Michael Jordan', 'SF': 'Scottie Pippen', 'PF': 'Dennis Rodman', 'C': 'Luc Longley'}, 'wonChampionship': True, 'pointsPerGame': 105.2}
## <class 'dict'>
1
2

如何操作 dict

在選擇 dict 中的資料我們使用中括號 [KEY] 搭配標籤(keys)。

season = "1995-1996"
team = "Chicago Bulls"
coach = "Phil Jackson"
records = {
    "wins": 72,
    "losses": 10
}
starting_lineup = {
    "PG": "Ron Harper",
    "SG": "Michael Jordan",
    "SF": "Scottie Pippen",
    "PF": "Dennis Rodman",
    "C": "Luc Longley"
}
won_championship = True
points_per_game = 105.2

best_chicago_bulls = {
    "season": season,
    "team": team,
    "coach": coach,
    "records": records,
    "startingLineup": starting_lineup,
    "wonChampionship": won_championship,
    "pointsPerGame": points_per_game
}
print(best_chicago_bulls["season"])
print(best_chicago_bulls["team"])
print(best_chicago_bulls["coach"])
print(best_chicago_bulls["records"])
print(best_chicago_bulls["startingLineup"])
print(best_chicago_bulls["wonChampionship"])
print(best_chicago_bulls["pointsPerGame"])
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
## 1995-1996
## Chicago Bulls
## Phil Jackson
## {'wins': 72, 'losses': 10}
## {'PG': 'Ron Harper', 'SG': 'Michael Jordan', 'SF': 'Scottie Pippen', 'PF': 'Dennis Rodman', 'C': 'Luc Longley'}
## True
## 105.2
1
2
3
4
5
6
7

由 dict 刪除我們可以使用 dict.pop(k, None) 將指定的 key 拋出,假如找不到就拋出 None;例如將 "pointsPerGame" 拋出並且以 points_per_game 接住。

season = "1995-1996"
team = "Chicago Bulls"
coach = "Phil Jackson"
records = {
    "wins": 72,
    "losses": 10
}
starting_lineup = {
    "PG": "Ron Harper",
    "SG": "Michael Jordan",
    "SF": "Scottie Pippen",
    "PF": "Dennis Rodman",
    "C": "Luc Longley"
}
won_championship = True
points_per_game = 105.2

best_chicago_bulls = {
    "season": season,
    "team": team,
    "coach": coach,
    "records": records,
    "startingLineup": starting_lineup,
    "wonChampionship": won_championship,
    "pointsPerGame": points_per_game
}
points_per_game = best_chicago_bulls.pop("pointsPerGame", None)
print(best_chicago_bulls)
print(points_per_game)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
## {'season': '1995-1996', 'team': 'Chicago Bulls', 'coach': 'Phil Jackson', 'records': {'wins': 72, 'losses': 10}, 'startingLineup': {'PG': 'Ron Harper', 'SG': 'Michael Jordan', 'SF': 'Scottie Pippen', 'PF': 'Dennis Rodman', 'C': 'Luc Longley'}, 'wonChampionship': True}
## 105.2
1
2

於 dict 新增可以直接宣告 dict["key"] = value

season = "1995-1996"
team = "Chicago Bulls"
coach = "Phil Jackson"
records = {
    "wins": 72,
    "losses": 10
}
starting_lineup = {
    "PG": "Ron Harper",
    "SG": "Michael Jordan",
    "SF": "Scottie Pippen",
    "PF": "Dennis Rodman",
    "C": "Luc Longley"
}
won_championship = True
points_per_game = 105.2

best_chicago_bulls = {
    "season": season,
    "team": team,
    "coach": coach,
    "records": records,
    "startingLineup": starting_lineup,
    "wonChampionship": won_championship
}
print(best_chicago_bulls) # without pointsPerGame
best_chicago_bulls["pointsPerGame"] = points_per_game
print(best_chicago_bulls) # with pointsPerGame
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
## {'season': '1995-1996', 'team': 'Chicago Bulls', 'coach': 'Phil Jackson', 'records': {'wins': 72, 'losses': 10}, 'startingLineup': {'PG': 'Ron Harper', 'SG': 'Michael Jordan', 'SF': 'Scottie Pippen', 'PF': 'Dennis Rodman', 'C': 'Luc Longley'}, 'wonChampionship': True}
## {'season': '1995-1996', 'team': 'Chicago Bulls', 'coach': 'Phil Jackson', 'records': {'wins': 72, 'losses': 10}, 'startingLineup': {'PG': 'Ron Harper', 'SG': 'Michael Jordan', 'SF': 'Scottie Pippen', 'PF': 'Dennis Rodman', 'C': 'Luc Longley'}, 'wonChampionship': True, 'pointsPerGame': 105.2}
1
2

使用 .keys().values().items() 可以分別取出 dict 中的所有標籤(Keys)、所有資料(Values)以及標籤加上資料(Items)。

season = "1995-1996"
team = "Chicago Bulls"
coach = "Phil Jackson"
records = {
    "wins": 72,
    "losses": 10
}
starting_lineup = {
    "PG": "Ron Harper",
    "SG": "Michael Jordan",
    "SF": "Scottie Pippen",
    "PF": "Dennis Rodman",
    "C": "Luc Longley"
}
won_championship = True
points_per_game = 105.2

best_chicago_bulls = {
    "season": season,
    "team": team,
    "coach": coach,
    "records": records,
    "startingLineup": starting_lineup,
    "wonChampionship": won_championship,
    "pointsPerGame": points_per_game
}
print(best_chicago_bulls.keys())
print(best_chicago_bulls.values())
print(best_chicago_bulls.items())
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
## dict_keys(['season', 'team', 'coach', 'records', 'startingLineup', 'wonChampionship', 'pointsPerGame'])
## dict_values(['1995-1996', 'Chicago Bulls', 'Phil Jackson', {'wins': 72, 'losses': 10}, {'PG': 'Ron Harper', 'SG': 'Michael Jordan', 'SF': 'Scottie Pippen', 'PF': 'Dennis Rodman', 'C': 'Luc Longley'}, True, 105.2])
## dict_items([('season', '1995-1996'), ('team', 'Chicago Bulls'), ('coach', 'Phil Jackson'), ('records', {'wins': 72, 'losses': 10}), ('startingLineup', {'PG': 'Ron Harper', 'SG': 'Michael Jordan', 'SF': 'Scottie Pippen', 'PF': 'Dennis Rodman', 'C': 'Luc Longley'}), ('wonChampionship', True), ('pointsPerGame', 105.2)])
1
2
3

小結

在這個小節中我們從純量(scalars)邁向結構(collections),研究 Python 的基本資料結構,包含如何創建與操作 list、tuple、set 與 dict。

延伸閱讀