Try   HackMD

Python 容器資料型別

容器資料型別(Container Datatypes)就是為了更有效率處理資料所設計的資料型別。

如果說變數是一個盒子,一次只能放入一個值,在實務面上,我們有很多資料要處理,例如5x5的LED燈,假設我們想個別紀錄每個LED燈的亮度,那麼我們可能需要25個變數(當然也可以設計成用更少變數來儲存狀態)。

在討論那些特殊方法以前,更直觀的方式是發明一個擁有很多格子的箱子,甚至裡面可以編號,讓資料可以一次存放處理,也可以透過編號,快速取用。

這個同時有多個格子的箱子,就是我們接下來要介紹的容器資料型別。

Python內建的容器資料型別

在Python中,最常見的資料結構有這四個:

  • List(串列)
  • Tuple(元組)
  • Set(集合)
  • Dictionary(字典)

List

list是一個值可變、可重複、存放有順序性的資料結構。

宣告:使用[],使用序號存取

student_name = ["AAA", "BBB", "CCC"] student_score = [100, 90, 80] print(student_name[0]) print(student_score[0])

新增/刪除/修改list的值

  • .append:加入
  • .insert:插入
  • .remove: 刪除
  • .pop(): 取出與刪除
student_name = ["AAA", "BBB", "CCC"] print(student_name) #Append student_name.append("DDD") print("{0}".format(student_name)) #Insert student_name.insert(3,"EEE") print("{0}".format(student_name)) #Remove student_name.remove("DDD") print("{0}".format(student_name)) #Pop student_name.pop() print("{0}".format(student_name))

搜尋

使用 .index()

student_name = ["AAA", "BBB", "CCC"] print(student_name) print(student_name.index("CCC"))

取得長度

使用 len(list)

student = ["CCC","AAA","BBB","CCC"] print(len(student))

排序

  1. 使用sort()
  2. 可使用reverse=True參數設定排序順序
student_score = [80, 60 , 70, 90] student_score.sort(reverse=True) print(student_score) student_score.sort(reverse=False) print(student_score)

List中的List

很常用的技巧,例如用一個list儲存全班姓名、分數資訊

student_list = [["AAA", 100],["BBB", 80],["CCC", 70]] print(student_list)

Tuple

Tuple是一個值不可變、可重複、存放有順序性的資料結構。

宣告:使用()

student_id = (0,1,2)

Set

Set是一個值可變、不可重複、存放沒有順序性的資料結構。

宣告:使用{}

student = {1, 2, 2, 3} print(student)

Dictionary

Dictionary是一個值可變、可重複、存放使用唯一識別Key的資料結構。
由一組或多組key-value組成

宣告:使用{key: value}

student = {"AAA":100, "BBB":90, "CCC":80} print(student)

存取

student = {"AAA":[100, 90, 100], "BBB":[70, 80, 100], "CCC":[90, 60, 80]} print(student["AAA"]) print(student.keys()) print(student.values())

取得長度

使用len()

student = {"AAA":[100, 90, 100], "BBB":[70, 80, 100], "CCC":[90, 60, 80]} print(len(student))

結合List使用

student = {"AAA":[100, 90, 100], "BBB":[70, 80, 100], "CCC":[90, 60, 80]} print(student)

總結

以下是所有資料結構的使用方式與比較,資料結構的運用,視實務面選擇:

資料結構型態 初始化方式 是否有次序 儲存值是否可重複 儲存值是否可被修改
List list(), [] YES YES YES
Tuple tuple, () YES YES NO
Set set([]), {} NO NO YES
Dictionary dict(),{key:value} NO Key不可重複, Value可以 YES

隨堂練習

全班的成績如下表所示,請設計一個程式來計算全班數學科平均成績,並使用以下設計原則

  • 使用Dictionarylist儲存全班資料
姓名 國文科 英文科 數學科
Chaoyen 80 87 67
Joanne 76 80 95
Manchster 85 70 90

參考程式碼:https://repl.it/@ChaoyenWu/basicloopex

student_score = { "Chaoyen":[80, 87, 67], "Joanne":[76, 80, 95], "Manchster":[85, 70, 90], } math_sum = 0 #儲存全班數學成績的累計 math_sum += student_score.values[2] print(math_sum/len(student_score))
tags: Python程式設計入門