資工服學第十一組
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Write
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Help
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Write
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # 第11組 - Week2 Python入門 - 服務學習共筆 ## 變數的概念 * 指內容不一定固定的資料項目,這種資料的值通常會隨著程式執行而改變。 * **名稱 :** 每個變數都會有一個專有名稱方便識別。 * **儲存位址 :** 記憶體中變數內容存放的起始位置。 * **資料型態** (下面會再詳細說明) * **內容 :** 指變數的內容,意即變數的"值"。 Example: > 程式碼: > ```python= > x = "Hello World" # x 便是這個程式的一個變數 > ``` --- ## 基本輸入輸出 ### 介紹兩個函數 input( );print( ) * **input( ) :** > input( )函數可以用於取得使用者的輸入,( )內可以指定提示文字在input( )函數執行時輸出,使用者的**輸入會以字串回傳** * **print( ) :** > print( )函數可以字串形式輸出( )中內容 > 在( )中加入sep=' '可以指定每個輸出間的分割字元,預設為' ' > 在( )中加入end=' '可以指定輸出的最後一個字元,預設為'\n'(換行) Example: > 程式碼: > ```python= > x = input("請輸入一個字串") # input()函數的括號中可以自行設定提醒文字,請注意提醒文字像字串一樣需要用""或''包起來 > print (x) >``` > 輸入: > > 請輸入一個字串:Boki # 在後面接著打上你想輸入的字詞 > 輸出結果: > > Boki # 此時print(x)印出來的東西和你剛剛輸入的東西一樣,代表輸入的東西已經成功存到變數x裡面了 --- ## 資料型態 ### 1. 什麼是 "資料型態(Data Type)" * 每個物件都存有資料,而物件會擁有自己的「資料型態」。 * **用途**:約束資料的解釋,並決定可以做什麼樣的操作。程式運行中,需要將資料載入記憶體執行,而記憶體的空間有限,所以需要因應不同需求的資料給予不同長度的記憶體空間(資料型態),這麼一來處理資料時也更有效率。 * **簡單來說**:資料型態像是箱子的尺寸,箱子的大小關係到能放進去的東西有多大。 * **別稱**:資料型別或資料類型 ### 2. Python常見的資料型態 #### I. 數字 (Numbers): |型態   |中文 |能放的東西 | |-------|--------------|-------------| |int |整數 |1 | |float |浮點數(小數) |3.14159265359| |long |**卒於Python3**| | |complex|複數 |3+1.4i (3 + 1.4<font color="#f00">j</font>) <font color="#f00">*註</font>| ##### **int:** > 一般的程式語言在儲存整數時會有一定的限制。eg: 一般整數(32bits)、長整數(64bits);在python 3.0 發布後就去除這個限制,可以放任意大小的數值進去。(即使 int 包含了 long 的功能) > > ps. 在python中整數宣告可以在任意位置插入_(會被自動忽略,是為了方便計算較長的數值eg.1_000_000_000) Example: > 程式碼: > ```python= > x = 1 > y = 1_000_000_000 > ``` ##### **float:** > 相對複雜的小數運算,且非100%準確,會有誤差。 Example: > 程式碼: > ```python= > x = 3.14159265359 > ``` ##### **complex :** > <font color="#f00">*註</font>:虛數在數學中寫作' i ';但在python中要宣告一個虛數值時,要用 '<font color="#f00"> j </font>' 來表示! > (~~你高中就會學了,現在不重要~~) Example: > 程式碼: > ```python= > x = 3 + 1.4j > ``` #### II. 文字 (Text) |型態|中文|能放的東西| |-|-|-| |string|字串|<font color="#f00">'</font>Boki<font color="#f00">'</font> 或 <font color="#f00">"</font>Boki<font color="#f00">"</font>| > >使用上以成對 <font color="#f00">'</font> 單引號或 <font color="#f00">"</font> 雙引號把要寫進去的字串包起來 Example: > 程式碼: > ```python= > x = "Boki" > y = 'Boki' > ``` #### III. 串列 (List) >以<font color="#f00">[ ]</font>建立,元素有序的集合 Example: > 程式碼: > ```python= > x = [1, 2, 3] > ``` #### IV. 元組 (Tuple) > 使用上類似串列,但建立後無法重新賦值 > 以<font color="#f00">( )</font>建立 Example: > 程式碼: > ```python= > x = (1, 2, 3) > ``` #### V. 集合 (Set) > 不同於串列(List)和元組(Tuple),集合(Set)不具備順序,因此沒有索引(Index) > 使用以<font color="#f00">{ }</font>建立 Example: > 程式碼: > ```python= > x = {1 : 2} > ``` #### VI. 字典 (Dictionary) > 與集合(Set)相同,以<font color="#f00">{ }</font>建立;或使用<font color="#f00">dict( )</font>函數建立 > 不同於集合(Set),字典(Dictionary)包含 <font color="#f00">鍵(Key)</font> 和 <font color="#f00">值(Value)</font> > 使用時,只要輸入字典(Dictionary)中的鍵(Key),便可以得到對應的值(Value) > > <font color="#f00">●</font> 宣告字典時,**key 的值需要是唯一且不可變的**,也就是在寫程式時不可隨意更動,如整數、字串、tuple 等;而 **value 可以是任何的資料型態**,例如: 字串、整數、list、物件等等。 Example: > 程式碼: > ```python= > x = {key1: value1, key2: value2} # 每一組對應的key和value的中間會用' , '隔開 > print (x['key1']) > ``` > 執行結果: > > value1 # 只要輸入key值,就會得到對應的value值 #### VII. 布林值 (Boolean) > 布林值(Boolean)只存在三種值 <font color="#f00">True</font> , <font color="#f00">False</font> , <font color="#f00">None(未知)</font> > 布林(Bool)主要功能為判斷條件的成立與否。如果成立,布林值為 true;反之則為 false。 Example: > 程式碼: > ```python= > a = 6 # 宣告變數 a = 6 > b = 4 # 宣告變數 b = 4 > print (a > b) # 判斷 a 是否 > b > print (a == b) # 判斷 a 是否 = b (進行判斷時要用 == 來判斷兩邊的值是否相等) > print (a != b) # 判斷 a 是否 不 = b > print (a < b) # 判斷 a 是否 < b > ``` > 執行結果: > > True > False > True > False 補充 - bool( )函數: > 使用bool( )函數可以將資料轉化成布林值 > <font color="#f00">●</font> 只要資料是0或是空資料我們都視為 False ,其他皆視為True Example: > 程式碼: > ```python= > print(bool(1)) > print(bool(0)) > print(bool(1.0)) > print(bool(0.0)) > print(bool(())) > print(bool((2,3,4))) > print(bool([])) > print(bool([1,2,3])) > print(bool(None)) > ``` > 執行結果 > > True > False > True > False > False > True > False > True > False ### 3. 使用type( )函數檢視資料型態 Example: > 程式碼: > ```python= > a = 1 > print(type(a)) > ``` > 執行結果: > > <class 'int'> More Example: > 程式碼: > ```python= > b = 3.14159265359 # 這個是圓周率喔 ~ > c = 3 + 1.4j # python宣告虛數要打j > d = "Boki" # python宣告string(字串)要用""把要輸出的東西包起來 > e = [1, 2, 3] > f = (1, 2, 3) > g = {1 : 2} > h = True > i = False > > print (type(b)) > print (type(c)) > print (type(d)) > print (type(e)) > print (type(f)) > print (type(g)) > print (type(h)) > print (type(i)) > ``` > 執行結果: > > <class 'float'> > <class 'complex'> > <class 'str'> > <class 'list'> > <class 'tuple'> > <class 'dict'> > <class 'bool'> > <class 'bool'> **補充 - 用 len( )函數查看資料長度:** Example: > 程式碼: > ```python= > x = "Boki" > print (len(x)) > ``` > 執行結果: > > 4 # 因為"Boki"中有4個字母,所以長度為4 ### 3. 強制轉型 > 在python中我們可以用int( )、float( )、string( )等函數,將已宣告的變數強制轉型成你想要使用的資料型態。 Example: > 在基本輸入輸出那邊,我們已經學到,直接input( )的資料會預設成 string(字串) 回傳;若你想要輸入一個數值,並對他進行運算時,就需要用到 int( ) 或 float( ),將input( )進來的資料強制轉型成整數或浮點數(小數),來進行後續的運算。 首先是錯誤的例子: > 程式碼: >```python= > x = input("請輸入一個整數:") > print (x + 5) > ``` > 輸入: > > 請輸入一個整數:5 # 這時輸入的數字5會因為input()的特性,被預設存為一個 string(字串) > > 輸出: > > error > > 當你沒有做強制轉型時,你直接input()進來的任何數值或文字,都會自動判定成string(字串),字串是不能跟一般的數值做運算的,因此會顯示錯誤。 正確的寫法如下: > 程式碼: > ```python= > x = int(input("請輸入一個整數:")) > print (x + 5) > ``` > 輸入: > > 請輸入一個整數:5 # 這時候輸入的值會被int()函數強制轉型成整數 > > 輸出: > >   10 # 這時就能正常的進行運算了(YA! --- ## 條件 ### 1. 什麼是 "運算子(Operator)" * 在程式中提供運算功能的符號 * 分為算數運算、條件運算、邏輯運算、位元運算、指定運算 ### 2. Python常見的運算子 #### I. 算數運算子 * ~~如果你學過加減乘除,你就知道這些是什麼意思了喔~~! | 運算子 | 功能 | Example | Output | | ------ | ---------------------- | ------- | --- | | + | 加法 | 6 + 4 | 10 | | * | 乘法 | 6 * 4 | 24 | | / | 除法 | 6 / 4 | 1.5 | | % | 兩數相除取餘數 | 6 % 4 | 2 | | // | 地板除(兩數相除取整數) | 6 // 4 |1| | ** | 次方 | 6 ** 4 | 1296 | #### II. 指派運算子 <font color="#f00">●</font> 假設 : x = 5 , a 為任意常數 | 運算子 | 功能 | Example | Print(x) | | ------ | --------- | -------| --- | | = | 把右邊的值指派給左邊 | x = 5 | 5 | | += | x = x + a | x += 5 | 10 | | -= | x = x - a | x -= 5 | 0 | | **=* | x = x * a | x **=* 5 | 25 | | /= | x = x / a | x /= 5 | 1 | | %= | x = x % a | x %= 5 | 0 | | //= | x = x // a| x // 5 | 1 | | **= | x = x ** a| x **= 5| 3125 | #### III. 關係運算子 <font color="#f00">●</font> 假設 : x = 6 , y = 4 | 運算子 | 功能 | Example | Result | | -------- | -------- | -------- | -------- | | == | 比較左右兩邊的值是否相等 | x == y | False | | != | 比較左右兩邊的值是否相異 | x != y | True | | > | 比較左邊的值是否大於右邊 | x > y | True | | < | 比較左邊的值是否小於右邊 | x < y | False | | >= | 比較左邊的值是否大於等於右邊 | x >= y | True | | <= | 比較左邊的值是否小於等於右邊 | x <= y | False | #### IV. 邏輯運算子 | 運算子 | 意思 | Example | | ------ |:----------------- | ------- | | and | 且 (A和B兩者皆須成立) | A and B | | or | 或 (A和B其中一個成立) | A or B | | not | 非 (不是A \ 和A相反) | not A | * and 真值表 | A | B | A and B | |:---:|:---:|:-------:| | T | T | T | | T | F | F | | F | T | F | | F | F | F | * or 真值表 | A | B | A or B | |:---:|:---:|:------:| | T | T | T | | T | F | T | | F | T | T | | F | F | F | * not 真值表 | A | not A | |:---:|:-----:| | T | F | | F | T | 利用前面學的boolean(布林值)來驗證看看真值表吧! Example: > 程式碼: > ```python= > print (False and True) > print (True and False) > print (False or True) > print (not 5) > print (not 0) > ``` > 執行結果: > > False > False > False > True > False > True ### 3. 條件運算 #### 1). 什麼是條件運算? * 在程式中使用 根據指定程式的布林值為 真 / 假 決定接下來的動作 * **簡單來說 :** 這個部分就是我們日常生活中常常說的「如果 ... ,就會(發生) ...。」的敘述,只是換成在Python中使用的表現形式而已。 #### 2). Python中的條件運算 ##### I. if 敘述 Example: > ```python= > if conditions: > statement 1 conditions可以使用比較運算子來組合想要判斷的條件,最後在結尾的地方加上冒號' <font color="#f00">**:**</font> ',當條件成立時,就會執行statement 1。 > <font color="#f00">*註</font>:只要隸屬於if區塊要做的事情,都要有相同的縮排。 ##### II. if - else 敘述 Example: > ```python= > if conditions: > statement 1 > else: > statement 2 當conditions條件成立,執行statement 1,條件不成立時,則執行statement 2,同樣的注意else的結尾需加上冒號' <font color="#f00">:</font> '及區塊中的縮排。 ##### III. if - elif - else 敘述 Example: > ```python= > if conditions 1: > statement 1 > elif conditions 2: > statement 2 > else: > statement 3 如果有多個條件要進行判斷時,就可以使用這個語法,當conditions 1條件成立時,執行statement 1,當conditions 2條件成立,執行statement 2,都不成立,則執行statement 3。 --- ## 迴圈 ### 1. 什麼是 "迴圈(Loop)" * **迴圈 :** 是一種常用的流程控制工具,可以使程式在執行特定次數或特定條件成立後結束。 * **簡單來說 :** 先給電腦一個起始的值,接著告訴電腦要跑幾次,最後再告訴它每一次執行的動作是什麼。 * **補充**:談論迴圈時會常常看到一個名詞 - 迭代(Iteration),在程式中指具可變狀態的重複,而迴圈便是迭代的一種應用。 ### 2. Python常見的迴圈 #### I-I. range( )函數 * 在介紹Python的迴圈前,先介紹一種好用的函數 : range( ) * range( )的功能是生成從 start 的值開始到 <font color="#f00">不大於 \ 不小於</font> stop 的值結束的<font color="#f00">遞增 \ 遞減數列</font> * range( )使用時需要三個值 (start 起始, stop 結束, step 遞增/減值)<font color="#f00">*註</font> > <font color="#f00">*註</font>:start 和 step 可以省略不寫,當start 和 setp 被省略時,其預設值分別為0和1 Example: > 程式碼: > ```python= > range(10) # [0,1,2,3,4,5,6,7,8,9] 省略 start 和 step ,生成從0到9,公差為1的遞增數列 > range(3,10) # [3,4,5,6,7,8,9] 只省略 step,生成從3到9,公差為1的遞增數列 > range(2,11,2) # [2,4,6,8,10] 完全不省略,生成2到10,公差為2的遞增數列 > range(10,0,-1) # [10,9,8,7,6,5,4,3,2,1] 完全不省略,生成10到1,公差為(-1)的遞減數列 > ``` #### I. for loop * 單層 for loop > ```python= > for i in sequence: > loopbody > ``` <font color="#f00">注意</font>:在序列後面須加上冒號,而在 loopbody 前需要縮排。 **for** 和 **in** 之間要插入自訂變數(i),而在 **in** 後則可接一個序列(sequence),迴圈會依序從序列 (例如: 一連串清單資料,一組數字或一個名單) 裡取得元素,並將元素指派給前面自訂的變數,然後執行迴圈裡的內容。 > Example: >程式碼: >```python= >for i in range(2,15,2) > print(i,end=" ") >``` > 執行結果: > > 2 4 6 8 10 12 14 * 巢狀 for loop >```python= >for i in sequence1: > for j in sequence2: > loopbody >``` 巢狀 for loop 則是多層的迴圈,也就是迴圈中還有迴圈。 #### II. while loop >```python= >while condition: > loopbody >``` <font color="#f00">注意</font>:和 for loop 一樣,在condition後面須加上冒號,而在 loopbody 前需要縮排。 while 迴圈的 condition(boolean值) 是判斷迴圈是否繼續跑的依據,若不符合 condition 會直接跳出這個迴圈,反之符合 conditon 則會執行迴圈內的內容,如果執行的結果仍符合 condition 就會再次執行這個迴圈。 > <font color="#f00">補充</font>: >* 出現沒有辦法讓 condition 改變的狀況,會讓這個迴圈無限的循環時,這種迴圈稱之為無窮迴圈。 >* 巢狀 while loop 同樣也是多層的迴圈。 Example: >程式碼: >```python= >i = 1 >while i < 6: > print(i,end=" ") > i += 1 >``` > 執行結果: > > 1 2 3 4 5 ### 3. 迴圈控制 * 透過迴圈控制 我們可以精確的操作迴圈執行的次數 達到執行特定操作需求 #### I. break * 一旦程式執行到 break 函數不論當前迴圈執行的狀態 整個迴圈會直接中止 Example : ```Python= count=0 while true: if count >= 10 break; print(count) count = count + 1 ``` #### II. continue * 執行至 continue 時 僅本次迴圈結束 下一輪迴圈依舊會開始執行 Example : ```Python= count=0 while true: if count%2==0 count=count+1 continue print(count) count=count+1 ``` #### III. pass * 基本沒啥用 呵呵(燦笑 ## 好用的函數 ### 幫助運算 #### I. abs( ) - 絕對值 : 數學上的表示|x|,python上的表示abs(x) Example : > 程式碼: >```Python= > print(abs(-4)) > ``` > 執行結果 : > > 4 #### II. sum( ) - 加總 : 把範圍內的值加起來,也可配合前面range( )使用 Example : > 程式碼: > ```Python= > print(sum(1,2,3)) > ``` > > 執行結果 : > > 6 #### III. Max( )與min( ) - 取最大\最小值: 找出範圍內的最大或最小 Example : > 程式碼: > ```Python= > print(Max(1,2)) > ``` > 執行結果: > > 2 Example : > 程式碼: > ```Python= > print(min(4,5)) > ``` > 執行結果 : > > 4 #### IV. pow(x,y) : x的y次方 Example : > 程式碼: > ```Python= > pinrt(pow(2,3)) > ``` > 執行結果 : > > 8 #### V. round(x,n): 數字x在小數點後n位四捨五入 Example : > 程式碼: > ```Python= > print(round(90.7489,1)) > ``` > 執行結果 : > > 90.7 #### VI. sorted( ) - 排序 : 將元素由小排到大 Example : > ```Python= > mylist=[1,4,9,-5,3] > print(sorted(mylist))[-5,1,3,4,9] > ``` > Result : > > [-5,1,3,4,9] >那由大排到小呢? ```Python= print(sorted(mylist,reverse=True)) ``` >加上這行***reverse=True***就可以了 ### 酷東東 #### I. eval() : > 將字符串str當成有效的表達式來求值並返回計算結果,可以配合math當作機算機(eval(expression[, globals[, locals]]) > 常見作用大致有3 > 1.計算字符串中有效的表達式,並返回結果 Example : ```Python= print(eval("n + 4")) ``` Result : ```Python= 85 ``` > 2.將字符串轉成相應的對象 Example 1 : ```Python= a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]" b = eval(a) print(b) ``` Result 1 : ```Python= [[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]] ``` Example 2 : ```Python= a = "{1:‘xx‘,2:‘yy‘}" c = eval(a) print(c) ``` Result 2 : ```Python= {1: ‘xx‘, 2: ‘yy‘} ``` Example 3 : ```Python= a = "(1,2,3,4)" d = eval(a) print(d) ``` Result 3 : ```Python= (1, 2, 3, 4) ``` > 3.將利用反引號轉換的字符串再反轉回對象 Example : ```Python= list1 = [1,2,3,4,5] a = eval('list1') print(type(eval('list1'))) print(a) ``` Result : ```Python= <class 'list'> [1,2,3,4,5] ``` > <font color="#f00">●</font> 使用時請注意安全性,可以將字符串轉成表達式並執行,就可以利用執行系統命令,刪除文件等操作 #### II. f-string: >格式化字串實字(簡單來說,取代文字) Example : ```Python= name='john' print(f'my name is {name}.') ``` Result : ```Python= my name is john. ``` # Week3 ### 枚舉 enumerate() >枚舉函數用於將一個可遍歷的對象 Ex:String, List, Tuple ... 組成具索引的序列,並同時包含數據與指標 >語法:enumerate() 參數:sequence, start >sequence:函數的遍歷對象(需要可以迭代) start:指標的起始位置 Example 一般的for : ```Python= i = 0 seq = ['one', 'two', 'three'] for element in seq: print(i, seq[i]) i += 1 ``` Example 使用 enumerate(): ```Python= i = 0 seq = ['one', 'two', 'three'] for i, element in enumerate(seq): print(i, element) ``` Result : ```Python= 0 one 1 two 2 three ``` ### zip() >zip()可以將多個可迭代對象作為參數,把對象壓縮成一個個元組,這樣做可以減少使用的空間 >若對象間的元素數量不一致 則以長度最短的對象為基準 >輸出時,可以用list()轉換 >語法:zip(iterable_1, iterable_2, ..., iterable_n) 參數:iterable >iterable:為一個或多個可迭代對象 Example : ```Python= a = [1,2,3] b = [4,5,6] c = [4,5,6,7,8] zipped = zip(a,b) print(list(zipped)) print(list(zip(a,c))) a1, a2 = zip(*zip(a,b)) print(a1, a2) ``` Result : ```Python= [(1, 4), (2, 5), (3, 6)] [(1, 4), (2, 5), (3, 6)] (1, 2, 3) (4, 5, 6) ``` ### 迭代器(interator) >一個Python很猛的功能 一種訪問集合的方式 只能單向的訪問可迭代物件 >如圖 可迭代物件x透過inter()變成迭代器 再透過next()取得內部元素 > >![](https://i.imgur.com/EJJjVwg.png) Example : ```Python= x = [1, 2, 3] y = iter(x) z = iter(x) print(next(y)) print(next(y)) print(next(y)) print(next(z)) print(type(x)) print(type(y)) ``` Result : ```Python= 1 2 3 1 <class 'list'> <class 'list_iterator'> ``` >從上述程式碼可以看出: x為可迭代物件 y,z為相互沒有關係的迭代器且各自以某種規則輸出x中的元素 #### 所以到底在說什麼 > _iter_(): 回傳前一個iterator物件 而這個物件可以呼叫__next__函數 > _next_(): 實際執行iterator物件的迭代 Example : ```Python= list = [1, 2, 3, 4] mylist_interator = iter(list) #iter函數會回傳一個迭代器 並由變數mylist_interator儲存 i = next(mylist_interator) #開始迭代 調用預設的__next__()函數 print(i) i = next(mylist_interator) print(i) i = next(mylist_interator) print(i) i = next(mylist_interator) print(i) i = next(mylist_interator) #當無元素可以遍歷 回傳StopIteration 停止執行 print(i) ``` Result : ```Python= 1 2 3 4 Traceback (most recent call last): File "<string>", line 16, in <module> StopIteration ``` #### 隱式迭代器 >在Python中 迭代器為語言的基礎部分 且許多時候迭代器是不可見的 Example : ```Python= for value in sequence: print(value) ``` >上述程式碼展示了Python中常見的迭代 而其中並沒有出現迭代器 因為它們隱含在for語句中 #### 顯式迭代器 >雖然Python中 隱式迭代器十分常見 顯式迭代器仍可以被使用和定義 >對於一個可迭代物件 iter()可用於建立一個迭代物件 並通過next()函數對物件進行迭代 >這個函數使用__next__() 使它返回容器中的下一個元素 Example : ```Python= sequence = [1, 2, 3] it = iter(sequence) while True: try: value = next(it) except StopIteration: break print(value) ``` Result : ```Python= 1 2 3 ``` >對於任何定義的類別 都可以定義返回迭代器物件__iter__()的方法 >接著 迭代器物件需要定義返回下一個物件__next__()的方法 ### 生成器(generator) >生成器是一種迭代器 基本上是含有yield()函數的function * 生成器的特性 >I. 比起一般迭代器定義__next__(), 生成器呼叫__next__()的回傳值直接產生自yield()函數 因此可以使程式看起來更加精簡 >II. 具備惰性求值的特性 當生成器被呼叫後 generator function並不會一口氣跑完 而是停在yield()函數 直到__next__()被呼叫 才會繼續工作 >III. 因為執行一次只會提供一個返回值 而不需要大量空間儲存執行結果 因此較一般迭代節省空間 Example : ```Python= def my_range(n): i = 0 while i<n: print('stop before yield', str(i)) yield i i += 1 for i in my_range(5): print(i) ``` Result : ```Python= stop before yield 0 0 stop before yield 1 1 stop before yield 2 2 stop before yield 3 3 stop before yield 4 4 ``` >從上面可以看出 在呼叫my_range()後 while迴圈並沒有馬上print出5行'stop before yield...' 而是先印出一行 並等待for迴圈下次呼叫

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully