Jia-Liang Lu
    • Create new note
    • Create a note from template
      • 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
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me 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
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control 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
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me 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
    1
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    <style> .red { color: red; } .blue{ color: blue; } .green{ color: green; } </style> # list、tuple、set與dict ## 6-1 list (串列) - Definition: 1. 由一連串資料所組成 2. 資料是有順序的 3. 是可以改變的(mutable)的序列(suquence) 4. list的前後以中括號表示 5. list裡面的資料已逗號隔開 6. list裡面資料的型別可以不同 ``` # 包含5個元素的list [1, "Taipei", 3.14, "NTNU", -43] # 元素相同但順序不同,表示不同串列 [-43, "NTNU", 3.14, "Taipei",1 ] ``` ### 6-1-1 建立串列(list) ``` # 建立空串列 >>> list1 = list() >>> list1 = [] # 建立包含1, "Taipei", 3.14, "NTNU", -43的list >>> list2 = list([1, "Taipei", 3.14, "NTNU", -43]) >>> list2 = [1, "Taipei", 3.14, "NTNU", -43] >>> print(list2) [1, "Taipei", 3.14, "NTNU", -43] ``` 除此之外,我們可以從字串或range物件建立list ``` # 從list中建立'N', 'T', 'N', 'U'的list >>> list3 = list("NTNU") >>> print(list3) ['N', 'T', 'N', 'U'] # 下方寫法與上方寫法意義不同 >>> list3 = list["NTNU"] >>> print(list3) ["NTNU"] # 從range物件建立包含0, 1, 2, 3, 4, 5 >>> list4 = list(range(6)) >>> list5 = list(range(10,2,-2)) >>> print(list4) [0, 1, 2, 3, 4, 5] >>> print(list5) [10, 8, 6, 4] ``` - 使用str.split([sep])的方法: 1. 根據選擇性參數sep所指定的分隔字串將字串分隔成串列然後回傳該串列 2. 參數sep可以省略不寫,表示為空白 ``` # 根據空白將字串分隔成串列 >>> print("NTNU".split()) ['N', 'T', 'N', 'U'] # 根據逗號將字串分隔成串列 >>> print("N,T,N,,U,".split(',')) ['N', 'T', 'N', '', 'U', ''] ``` ### 6-1-2 list的內建函式 - len(L): 回傳list L的長度,也就是list內的元素個數 - max(L): 回傳list L中元素最大的值 - min(L): 回傳list L中元素最小的值 - sum(L): 回傳list L中所有元素的總和 ``` # 透過len()函式,得出句子中的charactar個數 >>> list6 = list("NTNU is a college where I studied at.") >>> print(len(list6)) 36 ``` - random模組的shuffle(L)函式可以將串列參數,也就是L的元素隨機重排 - random模組的choice(L)函式可以從串列L中隨機挑選一個元素 ``` >>> import random >>> L=list(range(10)) >>> random.shuffle(L) >>> print(L) [4, 2, 8, 7, 1, 0, 3, 6, 5, 9] >>> print(random.choice(L)) 5 ``` ### 6-1-3 連接運算子 - "+"運算子可以用來連接不同的list ``` >>> list1 = list(range(5)) >>> list2 = list("NTNU") >>> list3 = list1 + list2 >>> print(list3) [0, 1, 2, 3, 4, 'N', 'T', 'N', 'U'] ``` ### 6-1-4 重複運算子 - "*"運算子可以用來重複同一個list ``` >>> list1 = list(range(5)) >>> list2 = list1*2 >>> print(list2) [0, 1, 2, 3, 4, 0, 1, 2, 3, 4] ``` ### 6-1-5 比較運算子 - 比較運算子如:>, <, >=, <=, ==, != - 可以用來比較list的大小或是否相等 - 比較的方法為: 1. 從兩個list的第1個元素開始比較 2. 若不相等則顯示比較結果 3. 若相等則繼續必較第二個元素 ``` >>> print(['a','B','c','d']>['A','b','C','d']) True >>> print(['我', '是', 'A']<['我', '是', 'b']) True ``` ### 6-1-6 in 與 not in 運算子 - in 運算子可以檢查某個元素是否在list裡 - not in 運算子可以檢查某個元素是否不在list裡 - 回傳值是True/False ``` >>> list = [1, "Taipei", 3.14, "NTNU", -43] >>> print("Taipei" in list1) True >>> print("USA" not in list1) True ``` ### 6-1-7 索引(index)與片段運算子 - 使用片段運算子可以取得list的元素 | index | 0 | 1 | 2 | 3 | 4 | 5 | | --- | --- | --- | --- | --- | --- | --- | | content | A | B | c | d | E | f | | index | -6 | -5 | -4 | -3 | -2 | -1 | ``` >>> L = ['A', 'B', 'c', 'd', 'E', 'f'] >>> print(L[:3]) ['A', 'B', 'c'] >>> print(L[5:]) ['f'] >>> print(L[2:-1]) ['c', 'd', 'E'] ``` - 將list做迭代的物件 ``` >>> L = [1,2,3,4,5] >>> sum = 0 >>> for i in L: sum+=i >>> print (sum) ``` ``` # 計算總和可以用sum(L) >>> L = [1,2,3,4,5] >>> print(sum(L)) 15 ``` ### 6-1-8 串列處理方法 - list.append(x): 將元素x加入list的尾端 - list.extend(L): 將list L加入另一個list的尾端 - list.insert(i, x): 將元素x加入到list中i元素之後 - list.remove(x): 從list中刪除第一個值為x的元素 ``` >>> list1 = [3, 4 ,5 ,6, 7] >>> for i in list1: >>> list1.remove(i) >>> print(list1, i) >>> print(list1) [4, 5, 6, 7] 3 [4, 6, 7] 5 [4, 6] 7 [4, 6] ``` - list.pop([i]): 從串列中刪除index為i的元素並回傳該元素。若沒有指定參數i,則刪除list中最後一個元素並回傳它 ``` >>> list1 = [1, 2 ,3] >>> list2 = list("NTNU") >>> list1.append(4) >>> print(list1) [1, 2, 3, 4] >>> list1.extend(list2) >>> print(list1) [1, 2, 3, 4, 'N', 'T', 'N', 'U'] # 不可以直接將list的物件帶進print函式中 >>>print(list1.extend(list2)) None ``` - list.index(x): 回傳元素x在list中第一次出現的位置 - list.count(x): 回傳元素x在list中出現的次數 - list.sort(): 將list內的元素由小到大排列 - list.reverse(x): 將list內的元素順序反轉過來 - list.copy(): 回傳串列的副本,副本和原始串列是不同的兩個物件 - list.clear(): 刪除list內的所有元素 ``` >>> list1 = [2, 1, 1, 3, 3, 3, 3, 4, 6, 1] >>> print(list1.index(3)) 3 >>> print(list1.count(3)) 4 >>> list1.sort() >>> print(list1) [1, 1, 1, 2, 3, 3, 3, 3, 4, 6] >>> list1.reverse() >>> print(list1) [6, 4, 3, 3, 3, 3, 2, 1, 1, 1] >>> list3 = list1.copy >>> print(list3) <built-in method copy of list object at 0x7c453658c200> >>> list1.clear() >>> print(list1) [] ``` ### 6-1-9 串列解析(list comprehension) - 串列解析(list comprehension)**提供一種更簡潔的方式來建立串列** - list的中括號裡面可以有for statement, 後面跟著for或if statement - 而串列的元素就是由這些運算式產生的 ``` >>> list1 = [i for i in range(0, 22, 2)] >>> list1 = [i*2 for i in range(11)] >>> list1 = [i for i in range(0, 102, 2) if i <= 20] >>> print(list1) [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20] ``` - 針對其他的list做計算 ``` >>> list1 = [0, -2, 4, -6, 8, -10, 12, -14, 16, -18, 20] >>> list2 = [abs(i//2) for i in list1] >>> print(list2) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # 當list的元素大於0時,運算abs(i//2) >>> list3 = [abs(i//2) for i in list1 if i < 0] [2, 4, 6, 8, 10] ``` ### 6-1-10 del statement - del statement可以刪除list中指定的元素 ``` >>> list1 = [0, -2, 4, -6, 8, -10, 12, -14, 16, -18, 20] # 指定刪除list1中的第2個元素(index從0開始) >>> del list1[2] >>> print(list1) [0, -2, -6, 8, -10, 12, -14, 16, -18, 20] >>> del list1[2:5] >>> print(list1) [0, -2, 12, -14, 16, -18, 20] # Clear all the element >>> del list[:] [] ``` ### 6-1-11 Two-dimension list - Two-dimension list是平面的二維空間 - 任何平面或二維矩陣都可以使用Two-dimension list來存放 | | 國文 | 數學 | 英文 | | -------- | -------- | -------- | -------- | | Student 1 | 100 | 60 | 91 | | Student 2 | 92 | 56 | 78 | | Student 3 | 82 | 86 | 77 | | Student 4 | 56 | 68 | 85 | | Student 5 | 95 | 77 | 81 | ``` >>> grade = [[100, 60, 91], [92, 56, 78], [82, 86, 77], [56, 68, 85], [95, 77, 81]] # 算出各位學生的分數總合和平均(至小數點第二位),並將這兩項資訊存在list中 >>> num_rows = len(grade) # 列數(學生數) >>> num_cols = len(grade[0]) # 行數(科目數) >>> for i in range(num_rows): >>> grade_sum = 0 >>> for j in range(num_cols): >>> grade_sum += grade[i][j] >>> grade[i].append(grade_sum) >>> avg = grade_sum / num_cols >>> grade[i].append(round(avg, 2)) # 將平均值四捨五入到小數點第二位 >>> print("Number of rows (students):", num_rows) >>> print("Number of columns (subjects):", num_cols) >>> for i in range(num_rows): >>> print("Student", i, "Total grade =", grade[i][num_cols]) >>> print("Student", i, "Avg =", grade[i][num_cols + 1]) Number of rows (students): 5 Number of columns (subjects): 3 Student 0 Total grade = 251 Student 0 Avg = 83.66666666666667 Student 1 Total grade = 226 Student 1 Avg = 75.33333333333333 Student 2 Total grade = 245 Student 2 Avg = 81.66666666666667 Student 3 Total grade = 209 Student 3 Avg = 69.66666666666667 Student 4 Total grade = 253 Student 4 Avg = 84.33333333333333 ``` ## 6-2 tuple (序對) - Definition: 1. tuple是由一連串的資料所組成 2. 資料是有順序的,且是**內容不可以改變**(immutable)的序列 3. tuple的前後是由小括號()所標示 4. tuple內的不同資料由逗號隔開 5. tuple內的資料的型別可以不同 ``` # 包含5個元素的tuple (1, "Taipei", 3.14, "NTNU", -43) # 元素相同但順序不同,表示不同串列 (-43, "NTNU", 3.14, "Taipei",1 ) ``` ### 6-2-1 建立tuple ``` # 建立一個空的tuple >>> tuple1 = tuple() >>> tuple = () >>> print(tuple1) () # 建立不為空的tuple >>> tuple2 = tuple((1, "Taipei", 3.14, "NTNU", -43)) >>> tuple2 = (1, "Taipei", 3.14, "NTNU", -43) >>> print(tuple2) (1, 'Taipei', 3.14, 'NTNU', -43) ``` - 透過字串、range物件或list建立物件 ``` # 透過字串建立物件 >>> tuple3 = tuple("NTNU") >>> print(tuple3) ('N', 'T', 'N', 'U') # 透過range物件建立物件 >>> tuple4 = tuple(i*2 for i in range(10)) >>> print(tuple4) (0, 2, 4, 6, 8, 10, 12, 14, 16, 18) # 透過list建立物件,從解析得到list來建立tuple >>> tuple5 = tuple([i*2 for i in range(10)]) >>> print(tuple5) (0, 2, 4, 6, 8, 10, 12, 14, 16, 18) ``` ### 6-2-2 tuple的運算 - tuple的運算類似於list,包含以下: ``` >>> tuple = (5, 2, 6, 0, 8, 1) # 找出tuple內的元素個數 >>> print(len(tuple)) 6 # 找出tuple內元素的最大值 >>> print(max(tuple)) 8 # 找出tuple內元素的最小值 >>> print(min(tuple)) 0 # 找出tuple內所有元素的總和 >>> print(sum(tuple)) 22 ``` - 因為list和tuple類似,只差在於tuple內的元素是不可改變的(immutable)。因此在list中介紹的連接運算子(+)、重複運算子(*)、比較運算子(>, <, >=, <=, ==, !=)、in/not in運算子、index運算子([ ])以及片段運算子([start:end]),**在tuple上都適用**。 - 這邊不提供程式碼(只要把list的[ ]改成( )即可) - 另外tuple.index(x), tuple.count(x)等函式也與上述list類似。可以自己去學習 - 但注意,因為tuple內的元素是不可改變的(immutable),因此上述**list的處理方法在tuple這邊不適用**! ## 6-3 set (集合) - set**沒有順序的概念**、**不能重複**且**內容可以改變** - 概念就如同數學上的集合(set) - 集合的前後以大括號表示{ } - set裡面的資料以逗號相隔開,且資料的型別可以不同但元素不能重複 ``` # 包含5個元素的set {1, "Taipei", 3.14, "NTNU", -43} # 若元素相同但順序不同,仍表示相同集合 {-43, "NTNU", 3.14, "Taipei", 1} ``` :::success - set和list一樣可以用來存放多筆資料 - 差別在於set中的元素沒有順序的概念且不能重複 - 因此set在執行是比較有效率的 ::: ### 6-3-1 建立set ``` # 建立一個空的set >>> set1 = set() >>> print(set1) set() # 建立一個不為空的集合 >>> set2 = set({1, "Taipei", 3.14, "NTNU", -43}) >>> print(set2) {1, 3.14, -43, 'NTNU', 'Taipei'} ``` - 另外我們也可以像前述的list和tuple一樣,透過字串、range物件或list來建立集合(set) ``` # 透過字串來建立集合(set) >>> set3 = set("NTNU") >>> print(set3) {'U', 'T', 'N'} # 透過range物件來建立集合(set) >>> set4 = set(i for i in range(10) if i <= 5) >>> print(set4) {0, 1, 2, 3, 4, 5} # 透過list來建立集合(set) >>> set5 = set([i*2 for i in range(10) if i <= 5]) >>> print(set5) {0, 2, 4, 6, 8, 10} ``` ### 6-3-2 內建函式 - len(S): 計算set內元素的個數 - max(S): 找出set內最大的元素 - min(S): 找出set內最小的元素 - sum(S): 計算出set中所有元素的總和 - 另外因為set內的元素沒有順序的概念,因此random.shuffle()在set這邊不適用! ### 6-3-3 運算子 - 因為set沒有順序的概念,所以set中元素的位置並不是那麼重要 - 因此set不支援連接運算子(+)、重複運算子(* )、索引(index)運算子、片段運算子([start:end])以及其他和順序相關的運算 - 另外in/not in運算子在set是可以使用的 - 比較運算子: ``` >>> s1 = set({1, "Taipei", 3.14, "NTNU", -43}) >>> s2 = set({-43, "NTNU", 3.14, "Taipei", 1}) >>> s3 = set([1, 3.14, -43]) >>> s4 = set({"Taipei", "NTNU"}) # 檢查兩個集合是否相等(==) >>> print(s1 == s2) True # 檢查兩個集合是否不相等(!=) >>> print(s1 != s2) False # 檢查s3是否為s1的子集合(<=, >=) >>> print(s3 <= s1) True >>> print(s1 >= s3) True >>> print(s1 >= s2) True # 檢查s3是否為s1的真子集合(<, >) >>> print(s3 < s1) True >>> print(s1 > s3) True >>> print(s1 > s2) False ``` - 可以透過for迴圈來走訪set所有的元素 ``` >>> s1 = set([i+1 for i in range(10)]) >>> sum = 0 >>> for i in s1: >>> sum+=i >>> print("s1 =",s1) >>> print("sum =",sum) s1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} sum = 55 ``` ### 6-3-4 集合處理的方法 - 集合屬於set類別的物件。而在set類別內提供許多處理集合序列的方法 - 包含: 1. 新增:set.add(x) 2. 刪除:set.remove(x)、set.pop()、set.clear() 3. 複製:set.copy() ``` >>> S = set([i+1 for i in range(10)]) # 在set中新增一個元素 >>> S.add(11) >>> print("S = ", S) S = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11} # 在set中刪除特定元素 >>> S.remove(5) >>> print("S = ", S) S = {1, 2, 3, 4, 6, 7, 8, 9, 10, 11} # 在set中刪除一個元素並傳回 >>> S.pop() >>> print("S = ",S) S = {2, 3, 4, 6, 7, 8, 9, 10, 11} # 複製set至另一個set >>> s2 = S.copy >>> print("s2 = ",s2) s2 = <built-in method copy of set object at 0x7c433fd21700> # 刪除set內所有的元素 >>> S.clear() >>> print(S) set() ``` - 子集合/超集合 1. set.issubset(S) 2. set.issuperset(S) ``` >>> s1 = set({1, "Taipei", 3.14, "NTNU", -43}) >>> s2 = set({-43, "NTNU", 3.14, "Taipei", 1}) >>> s3 = set([1, 3.14, -43]) >>> s4 = set({"Taipei", "NTNU"}) # s3是s1的子集合(subset)嗎? >>> print(s3.issubset(s1)) True # s1是s3的超集合(superset)嗎? >>> print(s1.issuperset(s3)) True ``` - 集合運算 1. s1.isdisjoint(s2): s1和s2兩個集合**沒有相同的元素嗎**? ``` >>> s1 = set([1, 3.14, -43]) >>> s2 = set([2, 3, 4, 5]) >>> s3 = set([3.14, -43, 1]) >>> print(s1.isdisjoint(s2)) True >>> print(s1.isdisjoint(s3)) False # False表示兩個集合有相同的元素 ``` 2. s1.union(s2): 將s1和s2兩個集合進行聯集 3. s1.update(s2): 將s1和s2兩個集合進行聯集後的結果存在s1 ``` >>> s1 = set([1, 3, 5, 7]) >>> s2 = set([2, 3, 4, 5]) >>> s3 = set([0, 1 ,2, 3]) >>> s4 = s1.union(s3) >>> print("s4 = ", s4) s4 = {0, 1, 2, 3, 5, 7} >>> s2.update(s4) >>> print("s2 = ", s2) s2 = {0, 1, 2, 3, 4, 5, 7} ``` 4. s1.intersection(s2): 此函式會回傳s1和s2的交集元素 5. s1.intersection_update(s2): 此函式會找出s1和s2的交集,並存在原本的s1 ``` >>> s1 = set([1, 3, 5, 7]) >>> s2 = set([2, 3, 4, 5]) >>> s3 = set([0, 1 ,2, 3]) >>> s4 = s1.intersection(s3) >>> print("s4 = ", s4) s4 = {1, 3} >>> s2.intersection_update(s4) >>> print("s2 = ", s2) s2 = {3} ``` 6. s1.difference(s2): 此函式會回傳s1和s2的差集元素 7. s1.difference(s2): 此函式會找出s1和s2的差集,並存在原本的s1 ``` >>> s1 = set([1, 3, 5, 7]) >>> s2 = set([2, 3, 4, 5]) >>> s3 = set([0, 1 ,2, 3]) # s4 = s1-s3 >>> s4 = s1.difference(s3) >>> print("s4 = ", s4) s4 = {5, 7} # s5 = s3-s1 >>> s5 = s3.difference(s1) >>> print("s5 = ", s5) s5 = {0, 2} # s2 = s2-s4 >>> s2.difference_update(s4) >>> print("s2 = ", s2) s2 = {2, 3, 4} ``` 8. s1.symmetric_difference(s2): 此函式會回傳s1和s2的**對稱差集**元素 9. s1.symmetric_difference_update(s2): 此函式會計算s1和s2的**對稱差集**元素,並將結果存在s1 ``` >>> s1 = set([1, 3, 5, 7]) >>> s2 = set([2, 3, 4, 5]) >>> s3 = set([0, 1 ,2, 3]) # s4 = s1^s3 >>> s4 = s1.symmetric_difference(s3) >>> print("s4 = ", s4) s4 = {0, 2, 5, 7} # s2 = s2^s4 >>> s2.symmetric_difference_update(s4) >>> print("s2 = ", s2) s2 = {0, 3, 4, 7} ``` ## 6-4 dict (字典) - dict沒有順序的概念、key不能重複且內容可以改變 - 屬於對應型別(mapping type),也就是鍵值對(key:value pair) - 概念:以key作為索引來存取字典裡面的值(value) - 字典內的key/value pair以逗號隔開 ``` # 包含3個key-value的dict {"Name":"Vitas", "Age":23, "Gender":"male"} # 若key-value相同但順序不同,仍表示相同的字典(dict) {"Age":23, "Gender"="male", "Name":"Vitas"} ``` ### 6-4-1 建立字典(dict) ``` # 建立空的dict >>> dict1 = {} >>> dict1 = dict({}) >>> print(dict1) {} # 建立非空的dict >>> dict2 = {"Name":"Vitas", "Age":23, "Gender":"Male"} >>> dict3 = dict({"Name":"Vitas", "Age":23, "Gender":"male"}) >>> dict4 = (Name = Vitas, Age = 23, Gender = Male) # 透過建立多個tuples形成的list建立字典(dict) >>> dict5 = dict([("Name","Vitas"), ("Age", 23), ("Gender", "Male")]) # dict2 = dict3 = dict4 = dict5 >>> print(dict5) {'Name': 'Vitas', 'Age': 23, 'Gender': 'Male'} ``` ### 6-4-2 取得、新增、變更或刪除key-value pair ``` # 透過key,取得value >>> dict2 = {"Name":"Vitas", "Age":23, "Gender":"Male"} >>> print(dict2["Name"]) Vitas # 新增一個key-value pair >>> dict2["College"]="NTNU" >>> print(dict2) {'Name': 'Vitas', 'Age': 23, 'Gender': 'Male', 'College': 'NTNU'} # 修改一個key的value >>> dict2["Age"]=18 >>> print(dict2) {'Name': 'Vitas', 'Age': 18, 'Gender': 'Male', 'College': 'NTNU'} # 刪除一個key-value pair >>> del dict2["Gender"] >>> print(dict2) {'Name': 'Vitas', 'Age': 18, 'College': 'NTNU'} ``` ### 6-4-3 內建函式 - 這邊指介紹一個: len(dict) ``` >>> dict = {'Name': 'Vitas', 'Age': 23, 'Gender': 'Male', 'College': 'NTNU'} >>> print(len(dict)) 4 ``` ### 6-4-4 運算子 - 因為dict沒有順序的概念,所以dict中元素的位置並不是那麼重要 - 因此dict不支援連接運算子(+)、重複運算子(* )、索引(index)運算子、片段運算子([start:end])以及其他和順序相關的運算 - 另外in/not in運算子在set是可以使用的 ``` >>> dict = {'Name': 'Vitas', 'Age': 23, 'Gender': 'Male', 'College': 'NTNU'} >>> print("Name" in dict) True >>> print("name" not in dict) True # in/not in運算子只能找key,不能找value >>> print("Vitas" in dict) False ``` - 在比較運算子,dict僅能使用==, !=兩個運算子 - 至於其他包括>, <, >=, <= 等比較運算子 ``` >>> dict1 = {'Name': 'Vitas', 'Age': 23, 'Gender': 'Male', 'College': 'NTNU'} >>> dict2 = {'Name': 'Vitas', 'Age': 23, 'Gender': 'Male'} >>> dict3 = {'Gender': 'Male', 'Age': 23, 'College': 'NTNU', 'Name': 'Vitas'} >>> print(dict1 == dict2) False >>> print(dict1 == dict3) True ``` - 透過for迴圈走訪dict所有的key-value pair ``` >>> dict = {'Name': 'Vitas', 'Age': 23, 'Gender': 'Male', 'College': 'NTNU'} >>> for key in dict: >>> print("key :", key, ", value :", dict[key]) key : Name , value : Vitas key : Age , value : 23 key : Gender , value : Male key : College , value : NTNU ``` ### 6-4-5 dict處理的方法 - 字典是屬於dict類別的物件,dict類別內有幾個字典處理的方法 1. dict.get(key): 回傳dict中鍵=key的value 2. dict.pop(key): 回傳dict中鍵=key的value,並刪除此key-value pair 3. dict.popitem(): **隨機**回傳dict中鍵=key的value,並刪除此key-value pair ``` >>> dict = {'Name': 'Vitas', 'Age': 23, 'Gender': 'Male', 'College': 'NTNU'} >>> print(dict.get("College")) NTNU >>> print(dict.pop("Gender")) Male >>> print(dict) {'Name': 'Vitas', 'Age': 23, 'College': 'NTNU'} >>> print(dict.popitem()) ('College', 'NTNU') >>> print(dict) {'Name': 'Vitas', 'Age': 23} ``` 4. dict.keys(): 回傳dict中所有的key 5. dict.values(): 回傳dict中所有的value 6. dict.items(): 回傳dict中所有的key-value pair ``` >>> dict = {'Name': 'Vitas', 'Age': 23, 'Gender': 'Male', 'College': 'NTNU'} >>> print(dict.keys()) dict_keys(['Name', 'Age', 'Gender', 'College']) >>> print(dict.values()) dict_values(['Vitas', 23, 'Male', 'NTNU']) >>> print(dict.items()) dict_items([('Name', 'Vitas'), ('Age', 23), ('Gender', 'Male'), ('College', 'NTNU')]) # 可以轉換成序對方便使用 >>> print(tuple(dict.keys())) ('Name', 'Age', 'Gender', 'College') >>> print(tuple(dict.values())) ('Vitas', 23, 'Male', 'NTNU') >>> print(tuple(dict.items())) (('Name', 'Vitas'), ('Age', 23), ('Gender', 'Male'), ('College', 'NTNU')) ``` 7. dict.copy(): 傳回字典的副本,但是和原來的dict為不同的物件 ``` >>> dict1 = {'Name': 'Vitas', 'Age': 23, 'Gender': 'Male', 'College': 'NTNU'} >>> dict2 = dict1.copy >>> print(dict2) {'Name': 'Vitas', 'Age': 23, 'Gender': 'Male', 'College': 'NTNU'} >>> print(dict1 == dict2) True ``` 8. dict.clear(): 刪除字典中所有的key-value pair ``` >>> dict = {'Name': 'Vitas', 'Age': 23, 'Gender': 'Male', 'College': 'NTNU'} >>> dict.clear() >>> print(dict) {} ``` 9. dict1.update(dict2): 根據dict2這個字典,來更新dict1。也就是將兩個字典合併,**若有重複的key則以dict2的value表示 ** ``` >>> dict1 = {'Name': 'Vitas', 'Age': 23, 'Gender': 'Male', 'College': 'NTNU'} >>> dict2 = {'Name': 'Pei', 'Age': 23, 'College': 'NYCU', 'Major':'CS'} >>> dict1.update(dict2) >>> print(dict1) {'Name': 'Pei', 'Age': 23, 'Gender': 'Male', 'College': 'NYCU', 'Major': 'CS'} ```

    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