Cracked Head
    • 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
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # 3. 使用列表/集合/字典 ###### tags: `Python` - Python 教學 第三篇 使用列表/集合/字典 ::: info 以下程式碼無先後順序 無連貫性 推薦影片教學頻道: - 英文 : [Tech With Tim](https://www.youtube.com/c/TechWithTim/featured) - 中文 : [彭彭老師的程式教學](https://www.youtube.com/watch?v=wqRlKVRUV_k&list=PL-g0fdC5RMboYEyt6QS2iLb_1m7QcgfHk&index=1&t=24s) ::: ### 一、列表的使用 ```python= # 定義三個列表 一個字串 gg = "i am here~" courses1 = ["Math", "History", "Physics", "Compute"] courses2 = ["Art", "Life"] nums = [1, 5, 10, 8, 7, 2] #使用列表 # 取得列表長度 len(courses1) #取得courses1列表的長度 # 新增物件 courses1.append(gg) #新增gg到courses列表中 # ["Math", "History", "Physics", "Compute", "i am here~"] courses1.insert(2, gg) #將gg插入到courses1列表中第3格 # ["Math", "History", "i am here~", "Physics", "Compute"] courses1.extend(courses2) #將courses2列表中的物件加到courses1中 # ["Math", "History", "Physics", "Compute", "Art", "Life"] courses1.append(courses2) #將courses2整個列表加入倒courses1中 # ["Math", "History", "Physics", "Compute", ["Art", "Life"]] # 則 "Art" 等於 courses[4][0] => 列表名稱[列表第一層位置][列表第二層位置]. . . . # 整理列表 courses1.sort() # .sort() 會直接更改列表 整理全數字或全字串的列表 #字串=>字母順序 數字=>大小 從第0位置開始比對 # ['Compute', 'History', 'Math', 'Physics'] nums.sort() # [1, 2, 5, 7, 8, 10] nums.sort(reverse=True) # 可以使用 reverse=True 讓整理好的列表順序顛倒 # [10, 8, 7, 5, 2, 1] courses1.remove("Math") #從列表中移除一個物件 此例終將被移除的物件為 "Math" # ['History', 'Physics', 'Compute'] courses1.pop(2) #移除列表第三個物件 # ['Math', 'History', 'Compute'] max(nums) #數字列表中 最大的值 => 10 min(nums) #數字列表中 最小的值 => 1 courses1.index("History") #取得 "History" 在列表中的位置 => 1 string = " - ".join(courses1) #將列表攤平變成字串 以 " - " 分隔原先列表中各個物件 # "Math - History - Physics - Compute" ``` ### 二、集合的使用 - 集合通常是透過將列表轉換後取得 - 常用來判斷物件是否存在於列表中 ```python= #定義兩個列表 language = ["Taiwanese", "English", "Chinese", "Japanese"] I_can_say = ["Taiwanese", "English", "Taiwanese", "Portuguese"] #集合的使用 # 1. 將列表轉換為集合 language = set(language) I_can_say = set(I_can_say) # 2-1. 判斷物件是否存在 使用列表List print("Taiwanese" in I_can_say) #會輸出True => True 因為 "Taiwanese" 在列表中 #但是 這樣會跑過所有物件來判斷 而集合的不重複性會讓判斷速度優化 # 2-2. 判斷物件是否存在 使用集合Set print("Taiwanese" in set(I_can_say)) #會輸出True => True 因為 "Taiwanese" 在集合中 #將 I_can_say列表轉為Set集合後判斷 "Taiwanese" 是否在集合中 # 3-1. 對比列表物件 共同傭有物件 print(set(language).intersection(set(I_can_say))) # => {"Taiwanese", "English"} # 3-2. 對比列表物件 查看不同物件 => a.difference(b) => 會輸出 a有 但b沒有的 print(set(language).difference(set(I_can_say))) # => {"Japanese"} # 3-3. 對比列表物件 合併兩個集合中的物件 共同擁有的只會保留一個 保持集合的不重複性 print(set(language).union(set(I_can_say))) # {"Taiwanese", "English", "Chinese", "Japanese", "Portuguese"} ``` ### 三、字典的使用 - 名稱 對應 數值 - 常用於資料處理 ```python= # 例子 1 dictionary = {"a":"apple", "b":"banana", 1:"this is 1", 2:"this is 2", "2":2} # 名稱 -- 數值 # "a" -- "apple" # "b" -- "banana" # 1 -- "this is 1" # 2 -- "this is 2" # "2" -- int(2) #如果我想要取得整數 2 dictionary["2"] #想要取得 "apple" dictionary["a"] #想要取得 "this is 2" dictionary[2] #如果想要找一個值 但不確定存不存在 => dictionary.get(想找的key, 如果不存在的話輸出甚麼) dictionary.get("Am I Handsome?", "Not Found") #!!!進階例子!!! students = { "John" : { "name" : "John", "age" : 17, "gender" : "male", "working" : False, "habbits" : ["basket ball", "soccer", "tennis"], "grade" : "second-grade" }, "Alice" : { "name" : "Alice", "age" : 16, "gender" : "female", "working" : False, "habbits" : ["chess", "tennis"], "grade" : "first-grade" }, "Keven" : { "name" : "Keven", "age" : 18, "gender" : "male", "working" : True, "habbits" : ["basket ball", "tennis", "jogging"], "grade" : "third-grade" }, "Jarvis" : { "name" : "Jarvis", "age" : 18, "gender" : "male", "working" : True, "grade" : "third-grade" } } #將 students 字典第一層的key轉為列表一一提取到變數name for name in students.keys(): #如果 students 中的 key等於name 所對應到的 數值(字典) 中有"habbits"這個key的話 if "habbits" in students[name].keys(): print(name, "habbits", True) # 輸出學生名字並輸出True else: print(name, "habbits", False) # 否則輸出學生名字並輸出False] ``` 進階例子中 我們舉例有四位學生 John Alice Keven Jarvis 用字典 並用下面提供的迴圈 (下一篇會詳細介紹) 就可以尋找是否有人缺少資料 此例子中 學生 Jarvis 缺少興趣資料 habbits 所以會輸出 Jarvis habbits False ![](https://i.imgur.com/UHTgko3.png) ### [上一篇](https://hackmd.io/ciwsdYteTx227FSIs_3IjA?view) ### [下一篇](https://hackmd.io/sZPWfF2RSsaQb03i-gVMpQ?view)

    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