Python

tuple & dictionary & set

INFOR

100110

講師:張雲淞

  • 暱稱:章魚
  • 班級:223(三類)
  • 職位:外交長兼學術

JavaScript & DC Bot

放課(星期三)

前次社課複習

迴圈 & list

9/19

迴圈

For loop

for i in range(100):
    print("Hello")

While loop

n = int(input())
sum = i = 0
while i <= n:
    sum += i
    i += 1
print(sum)

break

強制跳出迴圈

continue

跳過當次迴圈

List

宣告與讀取

scores = [100, 90, 80, 70, 60]
print(scores[0])  # 100
print(scores[0:2])  # [100, 90]
print(scores[-3])  # 80
print(scores[2:])  # [80, 70, 60]
print(scores[:2])  # [100, 90]
  • 索引值從 0 開始計
  • : 可用於讀取多項,如 0:2、2:
  • 負的索引值即為從後方讀取

List

操作串列

list1 = [10, 20, 30, 40, 50]
del list1[2]       # 刪除項目 [10, 20, 40, 50]
list1.append(60)   # 新增項目 [10, 20, 40, 50, 60]
list1.remove(20)   # 刪除指定值 [10, 40, 50, 60]
list1.insert(1, 0) # 插入項目 [10, 0, 40, 50, 60]
print(max(list1), min(list), sep=" ") # 最大最小值 60 10
list1.reverse()    # 反轉 [60, 50, 40, 0, 10]
list1.sort()       # 整理 [0, 10, 40, 50, 60]

tuple

元組

(     ,)

tuple 怎麼念?

Python 的創造者

Guido van Rossum:

週一、三、五念 too-pull;

週二、四、六念 tub-pull,

週日我不會提到它。

上一堂的 list,這堂課的 tuple, dictionary, set 都是容器

list 和 tuple 都屬於序列的類型

  • 容器 (Container)
  • 序列 (Squence)
  • 不可變 (Immutable)

最明顯的特性

tuple 元組

tuple 元組:創建

# 創建一個 tuple
a = 12345, 54321, "Hello"
print("a:", a) # output: a: (12345, 54321, 'Hello')
b = (12345, 54321, "Hello")
print("b:", b) # output: b: (12345, 54321, 'Hello')

可以使用小括號,或直接以逗號分隔值創建

( )

這是小括號

[ ]

這是中括號

{ }

這是大括號

tuple 元組:創建

# 只有一個元素時
c = (7,) # 需加逗號

只有一個元素時,需加逗號

讓電腦知道這是 tuple,而不是運算使用的括號

tuple 元組:不可變

# tuple 的值不可變
d = (12345, 54321, "Hello")
d[0] = 926
# TypeError: 'tuple' object does not support item assignment

使用陣列的方式修改 tuple 的值,會出現報錯

也不能使用 del 刪除元素

tuple 元組:運算與操作

# tuple 的運算與操作
e = (1, 2, 3) + (4, 5, 6) # 組合 (1, 2, 3, 4, 5, 6)
f = (1, 2, 3) * 3   # 重複 (1, 2, 3, 1, 2, 3, 1, 2, 3)
g = 3 in (1, 2, 3)  # 判斷是否有某元素 true
h = len((1, 2, 3))    # 長度 3

雖元素不能編輯,但可以對整個 tuple 進行連接、重複等操作

tuple 元組:取值

# tuple 的取值
i = (1, 3, 5, 7, 9)
print(i[0])   # output: 1
print(i[2:4]) # output: (5, 7)
print(i[-1])  # output: 9

與 List 的取值方式相同

tuple 元組:封裝與拆封

# tuple 的封裝與解封
j = 1, 2, 3 # 封裝 (Packing)
x, y, z = j # 解封 (Unpacking) x: 1, y: 2, z: 3

需注意拆封時變數個數需與元素個數一致,否則會發生報錯

dictionary

字典

dictionary 字典

  • 類似於查字典,用索引找尋資料
  • 較方便查找資料
  • 通過「關鍵字 Key」回傳對應的「值 Value」
  • 沒有順序性

dictionary 字典:創建

# 創建一個 dictionary
a = {'name': 'cat', 'age': 6, 'eat': ['cake', 'meat']

每個值的結構是 key: value,key 可以是數字或字串,value 的資料型態則沒有限制

key 不能重複出現

dictionary 字典:讀取

# 讀取 dictionary 的值
b = {'name': 'cat', 'age': 6, 'eat': ['cake', 'meat']}
print(b['name'])       # output: cat
print(b['eat'][0])     # output: cake
print(b.get('age'))    # output: 6
print(b.get('height')) # output: None

可以通過中括號 ['key'] 或是 get('key') 取值,使用 get 取值時若 key 不存在,將會回傳 None

dictionary 字典:刪除值

# 刪除 dictionary 的值
e = {'name': 'cat', 'age': 6}
del e['name']
print(e) # {'age': 6}

del e
print(e) # NameError: name 'e' is not defined

通過 del 可以刪除 dict 中的一項或整個 dict

dictionary 字典:刪除值

# 刪除 dictionary 的值
e = {'name': 'cat', 'age': 6}
e.pop('name')
print(e) # {'age': 6}

e.clear()
print(e) # {}

亦可使用 pop('key') 刪除元素

通過 clear() 可以清空整個 dict

set

集合

set 集合

  • 無序、不重複的集合
  • 儲存不需要排序、索引的元素

set 集合:創建

# 創建一個 set
a = {1, 2, 3, 4, 5}
print(a) # output: {1, 2, 3, 4, 5}
b = {1, 2, 3, 3, 4, 5}
print(b) # output: {1, 2, 3, 4, 5}

set 使用大括號包裹

定義時若出現重複的值會被自動去除

set 集合:操作

# set 的各種操作
c = {1, 2, 3, 4, 5}
print(len(c)) # 取得長度 output: 5
c.add(4) # 新增元素,如已存在則不會新增
c.add(6)
print(c) # output: {1, 2, 3, 4, 5, 6}

c.remove(2) # 刪除元素,如果刪除不存在的元素會報錯
print(c) # output: {1, 3, 4, 5, 6}

取得長度、新增、刪除元素

set 集合:操作

# set 的各種操作
d = {1, 2, 3, 4, 5}
d.discard(3) # 刪除元素,刪除不存在的元素時不會報錯
print(d) # output: {1, 2, 4, 5}

d.clear()
print(d) # output: {}

刪除元素、清空集合

set 集合:集合運算

set 集合:集合運算

集合 方法 運算子
交集 a.intersection(b) a&b
聯集 a.onion(b) a|
差集 a.difference(b) a-b
對稱差集 a.symmetric_difference(b) a^b

有獎品 ^^

下週是段考前最後一次社課,記得來喔

下課囉

Python 第三堂社課

By 章魚

Python 第三堂社課

  • 51