1 of 61

Python 程式設計研習

蘇東興、鄭明昌、楊珺宇

明新科大資工系

110/9/5

https://mustbeai.blogspot.com/p/python.html

1

2 of 61

內容

  • 研習內容
  • Python 開發環境
  • Python 基本資料型態
  • Python 流程控制
  • Python Numpy
  • Python Pandas
  • Python MatPlotLib
  • 網路爬蟲與資料分析

2

3 of 61

評量

  • 平常表現(出席、發問、學習態度等) 20%
  • 平常作業、觀看教學影片 30%
  • 期中考25%
  • 期末考25%
  • 教學資料:http://mustbeai.blogspot.com--> Python 分頁

3

4 of 61

1. 研習內容

4

研 習 內 容

備 註

1

開發環境 Anaconda介紹

Python資料型別、變數與運算

Python資料結構 list、set、dict、tuple

Python 內建常用函數

安裝Anaconda 開發環境、使用Jupyter 開發介面

2

向量與矩陣運算-NumPy套件

資料處理分析-Pandas套件

檔案處理函數

3

資料視覺化-Matplotlib 套件

4

網頁爬蟲與 OpenData取得

5 of 61

Python 基本資料型態

  • 整數(int)可任意長度
    • A =100000000000000000000
    • Print(a)
  • 浮點數(float)精確度達小數點下15位
    • B = 1.23456
  • 布林(bool):
    • True 、False
  • 字串(str):
    • 單引號 ' 或雙引 " 號括起來
    • 若是用 3 個引號 (" " " 或 ' ' ' ) 括住, 則字串中就可以含有單、雙引號

5

6 of 61

Variable(變數)命名規則

  • 變數只能包括:數字、大小寫英文字及底線、大寫和小寫字母是不一樣的
  • 名稱開頭的第 1 個字不可為數字。
  • 名稱不可是 Python 的保留字

6

7 of 61

變數命名規則

7

Python 保留字

8 of 61

Operator(運算子)

8

9 of 61

運算優先順序

9

10 of 61

Comment(註解)

  • 單行註解與多行註解
    • # This is a comment
    • ’’’ Multiple lines comment

Step 1:

Step 2:

’’’

10

11 of 61

運算範例

  • Python運算範例:
    • x = 5
    • print(type(x)) # 顯示 "<class 'int'>"
    • print(x) # 顯示 "5"
    • print(x + 1) # 加法: 顯示 "6"
    • print(x - 1) # 減法: 顯示 "4"
    • print(x * 2) # 乘法: 顯示 "10"
    • print(x / 2) # 除法: 顯示 "2.5"
    • print(x // 2) # 整數除法: 顯示 "2"
    • print(x % 2) # 餘數: 顯示 "1"
    • print(x ** 2) # 指數: 顯示 "25"
    • x += 1
    • print(x) # 顯示 "6"
    • x *= 2
    • print(x) # 顯示 "12"

11

12 of 61

Python 物件

  • Python中的所有資料都是物件 (object),而物件的型別定義於類別 (class),例如整數的型別是int類別。
  • 類別內包含屬性 (attribute)與方法 (method)。
  • Python中的物件都有編號 (id)、型別 (type) 與值 (value) :
    • id(x)
    • type(x)
    • print(x)

12

>>> x = 100

>>> id(x)

1573412672

>>> type(x)

<class 'int'>

>>> print(x)

100

13 of 61

數學函數

  • 內建數值函式
    • abs(x)
    • min(x1, x2 [, x3…])
    • max(x1, x2 [, x3…])
    • hex(x)
    • oct(x)
    • bin(x)
    • int(x)
    • round(x [, precision]
    • pow(x, y)
    • float(x)
    • complex(x)

  • 數學函式(math 模組)
    • import math
    • math.ceil(x)
    • math.fabs(x)
    • math.factorial(x)
    • math.floor(x)
    • math.gcd(x, y)
    • math.exp(x
    • import random
    • random.randint(x, y)
    • random.random()
    • random.shuffle(x)

13

14 of 61

布林(Bool)運算範例

  • Python語言的布林(Boolean)資料型態可以使用True和False關鍵字來表示,如下所示:

x = True

y = False

  • 我們除了可以使用True和False關鍵字,下列變數值也視為False,如下所示:
    • 0、0.0:整數值0或浮點數值0.0。
    • []、()、{}:容器型態的空清單、空元組和空字典。
    • None:關鍵字None。

14

15 of 61

字串運算範例1/3

  • Python「字串」(Strings)並不能更改字串內容,所有字串變更都是建立一個全新字串。
  • Python字串是使用「'」單引號或「"」雙引號括起的一序列Unicode字元。

s1 = "學習Python語言程式設計"

s2 = 'Hello World!’

  • 上述程式碼的變數是字串資料型態,Python語言並沒有字元型態,當引號括起的字串只有1個時,就是字元,如下所示:

ch1 = "A"

ch2 = 'b'

15

16 of 61

字串運算範例2/3

  • 當在Python程式建立字串後,我們就可以顯示字串、計算字串長度、連接2個字串告格式化顯示字串內容。

str1 = 'hello' # 使用單引號建立字串

str2 = "python" # 使用雙引號建立字串

print(str1) # 顯示 "hello"

print(len(str1)) # 字串長度: 顯示 "5"

str3 = str1 + ' ' + str2 # 字串連接

print(str3) # 顯示 "hello python"

str4 = '%s %s %d' % (str1, str2, 12) # 格式化字串

print(str4) # 顯示 "hello python 12"

16

17 of 61

字串運算範例3/3

  • 重複運算子�"Oh!" * 3 => 'Oh!Oh!Oh!‘
  • 比較運算子 (>、<、>=、<=、==、!=)�"abc" == "ABC“ => False
  • in與not in運算子�"or" in "forever“ => True
  • 索引與片段運算子�s = "Python程式設計“�s[2:5] => 'tho‘�s[3:7] => 'hon程‘�s[6:-1] => '程式設'

17

18 of 61

字串函數1/2

  • Python字串物件提供一些好用的方法來處理字串(Python程式:Ch2_2_3e.py),如下所示:

s = "hello“

dir(s) # 顯示 string 所有函數

print(s.capitalize()) # 第1個字元大寫: 顯示 "Hello"

print(s.upper()) # 轉成大寫: 顯示 "HELLO"

print(s.rjust(7)) # 右邊填空白字元: 顯示 " hello"

print(s.center(7)) # 置中顯示: 顯示 " hello "

print(s.replace('l', 'L')) # 取代字串: 顯示 "heLLo"

print(' python '.strip()) # 刪除空白字元: 顯示 "python"

18

19 of 61

字串函數2/2

  • 字串轉換
    • str.upper(s)
    • str.lower(s)
    • str.swapcase(s)
    • str.replace(old, new)
    • str.capitalize(s)
    • str.title(s)
  • 字串測試str.isalpha(s)
    • str.isdigit(s)
    • str.isalnum(s)
    • str.isupper(s)
    • str.islower(s)
    • str.isidentifier(s)
    • str.isspace(s)
    • str.istitle(s)
  • 字串搜尋
    • str.count(s)
    • str.startswith(s)
    • str.endswith(s)
    • str.find(s)
    • str.rfind(s)
  • 刪除指定字元或空白
    • str.strip([chars])
    • str.lstrip([chars])
    • str.rstrip([chars])
  • 字串格式
    • str.center(width)
    • str.ljust(width)
    • str.rjust(width)
    • str.zfill(width)
    • str.format(spec)

19

20 of 61

數值與字串格式化 1/2

  • format() 函式將數值與字串格式化,其語法如下:

format(value[, spec])

參數spec的格式如下:

[[fill]align][sign][#][0][width][,][.precision][type]

  • 設定欄位寬度與對齊方式

  • 設定加上千分位符號

  • 設定二、八、十六進位表示法�並加上 '0b'、'0o' 或 '0x‘

  • 設定加上正負符號並在正負�和數字間的空位填滿0

20

>>> format(123, "^10")

' 123 '

>>> format(123, "$^10")

'$$$123$$$$'

>>> format(12345678, ",")

'12,345,678'

>>> format(65, "#b")

'0b1000001'

>>> format(123, "=+010")

'+000000123'

21 of 61

數值與字串格式化 2/2

  • 設定欄位寬度與表示法

  • 設定對齊方式 (數值預設為靠右) �與千分位符號

  • 設定字串的欄位寬度與對齊方式� (字串預設為靠左)

21

>>> format(1234.5678, "10.2f")

' 1234.57'

>>> format(1234.5678, "10.2e")

' 1.23e+03'

>>> format(1234.5678, "<15.3f")

'1234.568 '

>>> format("Hello, World!", "20")

'Hello, World! '

>>> format("Hello, World!", ">20")

' Hello, World!'

>>> format("Hello, World!", "^20")

' Hello, World! '

22 of 61

字串- (escape sequence)

  • escape sequence對於無法顯示在螢幕上的符號,例如換行,使用escape sequence(在這些符號的前面加上反斜線\),便能顯示出來。

22

Esc Seq

意 義

\\

印出反斜線 (\)

\'

印出單引號 (')

\"

印出雙引號 (")

\a

響鈴 (Bell)

\b

倒退鍵 (Backspace)

\f

換頁 (Formfeed)

\n

換行 (Linefeed)

\r

歸位 (Carriage Return)

\t

[Tab] 鍵 (Horizontal Tab)

\v

垂直定位 (Vertical Tab)

\ooo

ASCII字元 (ooo為八進位整數)

\xhh

ASCII字元 (hh為十六進位整數)

\N{name}

Unicode字元 (name為字元名稱)

\uxxxx

Unicode字元 (xxxx為16-bit十六進位整數)

\Uxxxxxxxx

Unicode字元 (xxxxxxxx為32-bit十六進位整數)

print("\"Python\"程式設計")

"Python"程式設計

print("\101")

A

print("\x41")

A

print("\u0041")

A

print ("\N{BLACK SPADE SUIT}")

23 of 61

Print-format

23

print("Hello World") #Hello World

a = 1

b = 'runoob‘

print(a,b) #1 runoob

print("aaa""bbb") #aaabbb

print("aaa","bbb") #aaa bbb

print("www","runoob","com",sep=".") # www.runoob.com

print(“%10d“%10) #靠右對齊

print(“%+10d“%10) #靠右對齊

print(“%-10d“%10) #靠左對齊

print(“% 10d“%10) #左側填空白

print(“%010d“%10) #左側填0

24 of 61

Print-format

24

print(“%7.3f“%12.34567)

print(“%7.3f“%2.34567)

print(“%7.3f“%11112.34567)

print(“%.*f“%(3, 2.34567)

# 12.345

# 2.345

#11112.345

#2.345

text = '%d %.2f %s' % (1, 99.3, 'Justin')�print(text)�#1 99.30 Justin�print('%d %.2f %s' % (1, 99.3, 'Justin'))�#1 99.30 Justin

25 of 61

Print-format

25

print("I'm %s. I'm %d year old" % (‘Chang', 30))

a = "I'm %s. I'm %d year old" % (‘Chang', 30)

print(a)

print("I'm %(name)s. I'm %(age)d year old" % {'name':'Vamei', 'age':99})

print(‘’Hello World‘’, end=‘’‘’) #不換行

print('', Same Line'')

print(‘’Hello World‘’, end=‘’,‘’) #不換行,加 “,”

print(''Same Line'')

26 of 61

Print-format

26

print('{0} is {1}!!'.format(‘Chang', ‘goodman'))�#Chang is goodmanar!!�print('{real} is {nick}!!'.format(real = ' Chang ', nick = ' goodman '))�#Chang is goodmanar!!�print( '{real} is {nick}!!'.format(nick = ' goodman ', real = ' Chang '))�#Chang is goodmanar!!�print('{0} is {nick}!!'.format(' Chang ', nick = ' goodman '))�#Chang is goodmanar!!�print('{name} is {age} years old!'.format(name = ' Chang ', age = 35))�#Chang is 35 years old!'

27 of 61

Print-format-repr

27

from datetime import datetime

now = datetime.now()

print(str(now)) #2017-04-22 15:41:33.012917

print(repr(now)) #datetime.datetime(2017, 4, 22, 15, 41, 33, 12917)

raw = ‘\n\t This is a \t line with format \t\n’

print(raw)

raw =r‘\n\t This is a \t line with format \t\n’

print(raw)

raw = repr(‘\n\t This is a \t line with format \t\n’)

print(raw)

#

# This is a line with format

#\n\t This is a \t line with format \t\n

#‘\n\t This is a \t line with format \t\n’

28 of 61

Print-format

  • %s    字符串 (採用str()的顯示)
  • %r    字符串 (採用repr()的顯示)
  • %c    单个字符
  • %b    二进制整数
  • %d    十进制整数
  • %i    十进制整数
  • %o    八进制整数
  • %x    十六进制整数
  • %e    指数 (基底写为e)
  • %E    指数 (基底写为E)
  • %f    浮点数
  • %F    浮点数,与上相同
  • %g    指数(e) 或浮点数 (根据显示长度)
  • %G    指数(E)或浮点数 (根据显示长度)

28

29 of 61

流程控制

  • Python流程控制可以配合條件運算式的條件來執行不同程式區塊(Blocks),或重複執行指定區塊的程式碼,流程控制主要分為兩種,如下所示:
    • 條件控制:條件控制是選擇題,分為單選、二選一或多選一,依照條件運算式的結果決定執行哪一個程式區塊的程式碼。
    • 迴圈控制:迴圈控制是重複執行程式區塊的程式碼,擁有一個結束條件可以結束迴圈的執行。

  • Python程式區塊是程式碼縮排相同數量的空白字元,一般是使用4個空白字元,所以,相同縮排的程式碼屬於同一個程式區塊。

29

30 of 61

條件控制 – if條件敘述

30

s = int(input("請輸入成績 => "))

if s >= 60:

print("成績及格!")

else:

print("成績不及格!")

t = int(input("請輸入氣溫 => "))

if t < 20:

print("加件外套!")

print("今天氣溫 = " + str(t))

a = int(input("請輸入年齡 => "))

if a < 13:

print("兒童")

elif a < 20:

print("青少年")

else:

print("成年人")

31 of 61

條件控制 – 單行條件敘述

  • Python語言並不支援「條件運算式」(Conditional Expressions),我們可以使用單行if/else條件敘述來代替,其語法如下所示:

變數 = 變數1 if 條件運算式 else 變數2

  • 上述指定敘述的「=」號右邊是單行if/else條件敘述,如果條件成立,就將變數指定成變數1的值;否則就是指定成變數2的值。例如:12/24制的時間轉換運算式(Python程式:Ch2_3_1c.py),如下所示:

h = h-12 if h >= 12 else h

31

32 of 61

迴圈(loop) 1/4

32

m = int(input('m: '))

s = 0

for i in range(1, m + 1):

s = s + i

print("總和 = " + str(s))

for i in range(5):

print(i,end”,”)

# 0,1,2,3,4

for i in range(2,6):

print(i,end”,”)

# 2,3,4,5

m = int(input('m: '))

s = 0

for i in range(1, m + 1, 2):

s = s + i

print("總和 = " + str(s))

33 of 61

迴圈(loop) 2/4

33

list1 = [15, 20, 33, 7, 8]

sum = 0

for i in list1:

sum = sum + i

print(“Sum:", sum)

fruits = ['banana', 'apple', 'mango']

for fruit in fruits:

print (‘fruit:', fruit )

#fruit:banana

#fruit:apple

#.......

for letter in 'Python':

print('char :', letter)

#char:P

#char:y

#....

34 of 61

迴圈(loop) 3/4

34

n = int(input("請輸入大於 1 的整數:"))

if(n == 2):

print("2 是質數!")

else:

for i in range(2, n):

if(n % i == 0):

print("%d is not prime!" % n)

break

else:

print("%d is prime!" % n)

for i in range(1,10):

for j in range(1,10):

product = i * j

print("%d*%d=%-2d " % (i, j, product), end="")

# -2d 靠左對齊

print()

  1. If the else statement is used with a for loop, the else statement is executed when the loop has exhausted iterating the list.
  2. If the else statement is used with a while loop, the else statement is executed when the condition becomes false.

35 of 61

迴圈(loop) 4/4

  • break:強制跳出 整個迴圈
  • continue:強制跳出本次迴圈,繼續進入下一圈
  • pass:不做任何事情,程式都將繼續

35

cnt=0�for c in ‘content’:� cnt+=1� if c == ‘t’:� break� print(c)��print(‘\n迴圈結束')�print(‘執行 %d 次' %cnt)

cnt=0�for c in ‘content’:� cnt+=1� if c == ‘t’:� continue� print(c)��print(‘\n迴圈結束')�print(‘執行 %d 次' %cnt)

cnt=0�for c in ‘content’:� cnt+=1� if c == ‘t’:� pass� print(c)��print(‘\n迴圈結束')�print(‘執行 %d 次' %cnt)

36 of 61

迴圈控制 – while條件迴圈

36

n = int(input(" n:"))

r = 1

m = 1

while m <= n:

r = r * m

m = m + 1

print("  n! = " + str(r))

count = 0

while count < 3:

print (count, " is less than 3" )

count = count + 1

else:

print (count, " is not less than 5“)

#0 is less than 3

#1 is less than 3

#2 is less than 3

#3 is not less than 3

37 of 61

函數-定義

  • return傳回函數值和結束函數的執行
  • 函數端設定參數(Parameters)
  • 呼叫端傳入引數(Arguments)

37

38 of 61

函數-定義 與呼叫

  • 使用return關鍵字傳回值。

38

def print_msg():

# 無參數函數

print(“Hello Python!")

def is_valid_num(no):

if no >= 0 and no <= 200.0:

return True

else:

return False

def convert_to_f(c):

f = (9.0 * c) / 5.0 +32

return c, f

print_msg()

if is_valid_num(100):

print("合法!")

else:

print("不合法")

c, f = convert_to_f(32)

print(“c,f:”,c,f)

39 of 61

函式的參數

  • 當參數屬於不可改變內容的物件時,例如數值、字串、tuple (序對),就會採取傳值呼叫 (call by value) ,下面是一個例子。
  • 當參數屬於可改變內容的物件時,例如list (串列)、set (集合)、dict (字典),就會採取傳址呼叫 (call by reference),下面是一個例子。

39

def swap(x, y):

temp = x

x = y

y = temp

a, b = 1, 2

print(a, b)

swap(a, b)

print(a, b)

def swap(x):

temp = x[0]

x[0] = x[1]

x[1] = temp

a = [1, 2]

print(a)

swap(a)

print(a)

40 of 61

關鍵字引數

  • Python預設採取位置引數 (position argument),但有些參數順序不好記,可以使用關鍵字引數 (keyword argument) 來做區分,在呼叫函式時指定引數所對應的參數名稱。

40

def trapezoidArea(top, bottom, height):

result = (top + bottom) * height / 2

print("這個梯形面積為", result)

trapezoidArea(10, 20, 5)

trapezoidArea(10, height = 5, bottom = 20)

trapezoidArea(height = 5, bottom = 20, top = 10)

41 of 61

預設引數值

  • 在定義函式時設定預設引數值 (default argument value)

41

def teaTime(dessert, drink = "紅茶"):

print("我的甜點是", dessert, ",飲料是", drink)

teaTime("馬卡龍", "咖啡")

teaTime("帕尼尼")

teaTime(dessert = "三明治", drink = "奶茶")

teaTime("紅豆餅", drink = "綠茶")

42 of 61

任意引數串列

  • Python支援任意引數串列 (arbitrary argument list) ,�函式接受不限定個數的參數

42

def add(*numbers):

total = 0

for i in numbers:

total = total + i

return total

print(add(1))

print(add(1, 2))

print(add(1, 2, 3))

print(add(1, 2, 3, 4))

print(add(1, 2, 3, 4, 5))

43 of 61

lambda運算式

Python提供lambda關鍵字用來建立小的匿名函式,其語法如下:

lambda arg1, arg2, …: expression

43

add = lambda x, y: x + y

print(add(1, 2))

3

print(add(50, -100))

-50

print(add(50, 3.8))

53.8

print(add(50, True))

51

print(add("abc", "de"))

abcde

44 of 61

Python模組與套件

  • Python模組是單一Python程式檔案,即副檔名.py的檔案,套件是一個目錄內含多個模組的集合,而且在根目錄包含Python檔案__init__.py。

44

45 of 61

使用Python模組與套件 – �匯入模組或套件

45

import random

list = [20, 16, 10, 5]

random.shuffle(list)

print( "随机排序列表 : ", list)

random.shuffle(list)

print ("随机排序列表 : ", list )

import random

target = random.randint(1, 100)

Target = random.random()

import random as r

target = r.randint(1,100)

from bs4 import BeautifulSoup

html_str = "<p>Hello World!</p>"

soup = BeautifulSoup(html_str, "lxml")

print(soup)

from random import seed, random

seed(100)

target = random(1,100)

from random import *

seed(100)

target = random

46 of 61

Contaoner(容器)型態

  • list
  • dic
  • set
  • tuple

46

47 of 61

list

  • Lists(清單、串列和列表)類似其他程式語言Arrays(陣列)。
  • 不同於字串型態的不能更改,清單允許更改(Mutable)內容,我們可以新增、刪除、插入和更改清單的項目(Items)。

47

48 of 61

List-基本用法

  • Python清單(Lists)是使用「[ ]」方括號括起的多個項目,每一個項目使用「,」逗號分隔

ls = list() #建立空list

ls = [] #建立空list

ls = list[1,2,3] # 建立清單

ls = [6,4,5] # 建立清單

print(ls, ls[2]) # 顯示 "[6, 4, 5] 5"

print(ls[-1]) # 負索引從最後開始: 顯示 "5"

ls[2] = "py" # 指定字串型態的項目

print(ls) # 顯示 "[6, 4, 'py']"

ls.append("bar") # 新增項目

print(ls) # 顯示 "[6, 4, 'py', 'bar']"

ele = ls.pop() # 取出最後項目

print(ele, ls) # 顯示 "bar [6, 4, 'py']"

48

49 of 61

List-split

  • Python清單可以在「[]」方括號中使用「:」符號的語法,即指定開始和結束來分割清單成為子清單(Python程式:Ch2_5_1a.py),如下所示:

nums = list(range(5)) # 建立一序列的整數清單

print(nums) # 顯示 "[0, 1, 2, 3, 4]"

print(nums[2:4]) # 切割索引2~4(不含4): 顯示 "[2, 3]"

print(nums[2:]) # 切割索引從2至最後: 顯示 "[2, 3, 4]"

print(nums[:2]) # 切割從開始至索引2(不含2): 顯示 "[0, 1]"

print(nums[:]) # 切割整個清單: 顯示 "[0, 1, 2, 3, 4]"

print(nums[:-1]) # 使用負索引切割: 顯示 "[0, 1, 2, 3]"

nums[2:4] = [7, 8] # 使用切割來指定子清單

print(nums) # 顯示 "[0, 1, 7, 8, 4]"

49

50 of 61

List-loop

  • Python程式是使用for迴圈走訪顯示清單的每一個項目(Python程式:Ch2_5_1b.py),如下所示:

animals = ['cat', 'dog', 'bat']

for animal in animals:

print(animal)

  • 上述for迴圈可以一一取出清單每一個項目和顯示出來,如果需要顯示清單各項目的索引值,我們需要使用enumerate()函數

for index, animal in enumerate(animals):

print(index, animal)

50

51 of 61

List- Functions

  • ls = [2,4,6,8,10]
  • len(ls) # 5
  • min(ls) # 1
  • max(ls) # 10
  • sum(ls) # 30
  • random.shuffle(ls) � # [6,4,2,20,8]
  • list.append(x)
  • list.extend(l)
  • list.insert(i, x)
  • list.remove(x)
  • list.pop([i])
  • list.index(x)
  • list.count(x)
  • list.sort()
  • list.reverse()
  • list.copy()
  • list.clear()

51

52 of 61

List

  • List Comprehension一種簡潔語法來建立清單。list1 = [x for x in range(5)] �# [0,1,2,3,4]list2 = [x*2 for x in range(5)] �# [0,2,4,6,8]�list3 = [x for x in range(10) if x % 2 == 0]�#[0,2,4,6,8]�list4 = [x*2 for x in range(10) if x % 2 == 0�#[0,4,8,12,16]

52

53 of 61

二維list

53

01 grades = [[85, 95, 90], [96, 92, 85], [88, 78, 86], [88, 80, 82], [80, 78, 75]]

02 for i in range(5):

03 subTotal = 0

04 for j in range(3):

05 subTotal += grades[i][j]

06 grades[i].append(subTotal)

07

08 for i in range(5):

09 print(“學生”, i + 1, “的總分是", grades[i][3])

54 of 61

Dic-字典

  • Dict(字典),沒有順序、沒有重複、可改變內容的多個鍵:值對 (key: value pair),是對映型別,以鍵 (key)為索引、存取字典裡面的值 (vale)。dic前後以大括號標示,裡面的鍵:值對以逗號隔開� d = {“cat”: “white”, “dog”: “black”} # 建立字典� w = d(“cat”) # w = “white”

print(d["cat"]) # 使用Key取得項目: 顯示 "white"

print("cat" in d) # 是否有Key: 顯示 "True"

d["pig"] = "pink" # 新增項目

print(d["pig"]) # 顯示 "pink"

print(d.get("monkey", "N/A")) # 取出項目+預設值: 顯示 "N/A"

print(d.get("pig", "N/A")) # 取出項目+預設值: 顯示 "pink"

del d["pig"] # 使用Key刪除項目

print(d.get("pig", "N/A")) # "pig"不存在: 顯示 "N/A"

54

55 of 61

Dic-探索字典

  • 使用for迴圈以鍵來探索字典

55

d = {"chicken": 2, "dog": 4, "cat": 4, "spider": 8}

for animal in d:

legs = d[animal]

print(animal, legs)

d = {"chicken": 2, "dog": 4, "cat": 4, "spider": 8}

for animal, legs in d.items():

print("動物: %s 有 %d 隻腳" % (animal, legs))

56 of 61

Dic – loop

d1 = {x:x*x for x in range(10)}

#{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

d2 = {x:x*x for x in range(10) if x % 2 == 1}�#{1: 1, 3: 9, 9: 81, 5: 25, 7: 49}。

56

57 of 61

Set – 集合的基本使用

  • Set使用「{}」大括號括起,每一個元素以「,」逗號分隔

animals = {"cat", "dog", "pig"} # 建立集合

print("cat" in animals) # 檢查是否有此元素: 顯示 "True"

print("fish" in animals) # 顯示 "False"

animals.add("fish") # 新增集合元素

print("fish" in animals) # 顯示 "True"

print(len(animals)) # 元素數: 顯示 "4"

animals.add("cat") # 新增存在的元素

print(len(animals)) # 顯示 "4"

animals.remove('cat') # 刪除集合元素

print(len(animals)) # 顯示 "3"

57

58 of 61

Set – 探索集合

  • 探索集合和探索清單是相同的。

animals = {"cat", "dog", "pig", "fish"} # 建立集合

for index, animal in enumerate(animals):

print('#%d: %s' % (index + 1, animal))

58

59 of 61

Set – 集合運算

  • 集合運算:交集、聯集和差集。 �A = {1, 2, 3, 4, 5} , B = {4, 5, 6, 7, 8}
  • intersection(交集)
    • C = A & B, C= A.intersection(B)
  • Union(聯集)
    • A | B, A.union(B)
  • Difference(差集)
    • A-B, A.difference(B)

59

60 of 61

Tuple

  • Tuple(元組)是使用「()」括號來建立,使用「,」逗號分隔項目, tuple 不可修改

t = (5, 6, 7, 8) # 建立元組

print(type(t)) # 顯示 "<class 'tuple'>"

print(t) # 顯示 "(5, 6, 7, 8)"

print(t[0]) # 顯示 "5"

print(t[1]) # 顯示 "6"

print(t[-1]) # 顯示 "8"

print(t[-2]) # 顯示 "7"

for ele in t: # 走訪項目

print(ele, end=" ") # 顯示 "5, 6, 7, 8"

60

61 of 61

61

The End