中興大學資訊社
      • 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
    • Engagement control
    • 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 Versions and GitHub Sync Note Insights Sharing URL Help
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
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
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    --- title: 容器 - Python 教學 description: 中興大學資訊研究社1091學期程式分享會主題社課 tags: Python --- ###### [Python 教學/](/@NCHUIT/py) # 容器 > [name=VJ][time= 109,10,13] > [name=Hui][time= 110,10,21] --- 翻譯 | `int` | `float` | `str` | `bool` | | ----- | ------- | ----- | ------ | | 整數 | 浮點數 | 字串 | 布林值 | | `list` | `dict` | `tuple` | `set` | | ------ | ------ | ------- | ----- | | 串列 | 字典 | 元組 | 集合 | --- ## 串列 (List) List 在 Python 中常常用來儲存連續性的資料,在使用上與 C/C++ 中的 **陣列(array)** 有許多相似之處。 不過**list**這個字本身就是不包含長度的意思,在建立之初不用(也不可以)宣告長度,用實際物品比喻的話可以理解為單字卡(下圖) >btw 如果想出建立有初始長度的請搭配generator使用 ![](https://i.imgur.com/r35oBTz.jpg) 並且能藉由自帶的功能(methon)來實現元素的新增或移除 --- Python 建立 List 時以中括號將元素包起來,<br>值得一提的是:List 能將 **不同型態** 的資料放在一起 ```python example = [123, 'word', True, [], {}] ``` | 索引 | example | | ---- | -------- | | 0 | `123` | | 1 | `'word'` | | 2 | `True` | | 3 | `[]` | | 4 | `{}` | --- ## 字典 (Dictionary) Dictionary 與 List 的區別就只是包著的符號改成大括號、需要特別宣告 ***鍵值(key)*** 而已。 ```python= example = {4:123, 2:'word', 0:True} ``` | 索引 | example | | ---- | -------- | | 4 | `123` | | 2 | `'word'` | | 0 | `True` | --- ### `dict`補充說明 ``dict`` 是 **無序** 的。 ``dict`` 的 ***鍵值(key)*** **只可以**是<br>``int``, ``str``, 或 ``tuple`` ```python= ex1 = {3:[], 27:[]} # key 為 int 的 dict ex2 = {'m':[], 'l':[]} # key 為 str 的 dict ex3 = {(7,9):[], (4,2):[]} # key 為 tuple 的 dict ``` --- #### 資料型態 `tuple, set` 補充 `tuple, set` 類似 `list` 什麼都能塞,但 ```python= t = (1,'words',False) # tuple 不能變動 s = {0.0,True,'luv'} # set 無法取 index ``` --- ##### 延伸 `tuple, set, list` 可以互相 **轉型** ```python= t = (1,'words',False) s = {2.0,True,'luv'} l = [False,0,'abc'] #下面隨便看看就好,傷眼睛 ts = tuple(s) #ts = (2.0,True,'luv') tl = tuple(l) #tl = (False,0,'abc') st = set(t) #st = {1,'words',False} sl = set(l) #sl = {False,0,'abc'} lt = list(t) #lt = [1,'words',False] ls = list(s) #ls = [2.0,True,'luv'] ``` --- ::: spoiler 練習 ```python= ex = {'a':(True, False), 'b':[3, 2, 7]} print(ex['b'][2]) #輸出: 7 ``` | 索引 | ex | | ---- | ------------- | | a | `(True, False)` | | b | `[3, 2, 7]` | --- ::: 建立一個包含<br>全是 `int` 的 `list` 和全是 `bool` 的 `tuple`、<br>索引值為 `str` 的 `dict` --- ## 元素存取 ``list, dict`` 中要存取其中的某一筆資料,直接在後面加上 ``[index]`` 即可 ```python= e = ['word', 123, False] print(e[0]) # list 索引值從 0 開始 #輸出: word d = {'m':420,'w':327,'d':105} print(d['w']) # 字串索引 dict 取元素需打上'' #輸出: 327 ``` 補充: `str` 取索引值會取得位於該索引值上的字元 ```python= w = 'lth' print(w[2]) #輸出: h ``` --- ``list`` 中如果取 index 為 -1 即為 ``list`` 中最後一個元素 ```python= e = ['word', 123, False] print(e[-1]) #輸出: False print(e[-2]) #輸出: 123 ...依此類推 ``` 注意: index 取負號只限 `list` 或 `tuple` --- ## 元素變換 ### 範例 ```python= e = ['word', 123, False] e[-1] = 2.0 print(e) #輸出: ['word', 123, 2.0] d = {'m':420,'w':327,'d':104} d['d'] += 1 #在原有的數字上+1 print(d) #輸出: {'m':420,'w':327,'d':105} ``` --- ::: spoiler 練習 將字串:`'hello'`取代為 `list:['hello']` ```python= ex[0] = ['hello'] ``` --- ::: 試試看 在以下程式碼中間加一行使輸出為 hello ```python= ex = ['hello', 123, False] #加在這 print(ex[0][0]) #原輸出: h ``` --- ## `list` 取範圍 List 中還有一個特性就是能指定範圍。 使用中括號 ``[a:b]`` 即為 `list` 索引值 a~b 的部分,如 ```python= list_example=['0',1,'2',3,'4',5,'6'] print(list_example[2:-1]) #[:-#]有別於[-#:]、[-#] #輸出:['2', 3, '4', 5] ``` --- ### 補充 取範圍還有其他特定位置的用法,如 省略起始: ``[:9]``$\iff$``[0:9]`` 省略結尾: ``[1:]``$\iff$``[1:len(list)]`` 取範圍同樣適用 ``str, tuple``,但 `tuple` 只能取、不能動。另因為 `dict` 無序,無法取範圍。 ``len()`` : 取得``list``有幾個元素、或``dict``有幾組資料 --- ::: spoiler 練習 ```python= print(ex[-4:]) #輸出: hijk print(ex[:5]) #輸出: abcde print(ex[1:-4]) #輸出: bcdefg ``` --- ::: 試對字串 `ex` 取範圍 ```python= ex = 'abcdefghijk' ``` 輸出 ``` hijk abcde bcdefg ``` --- ## `list` 新增元素 ### 1.`append(object)` `append()` 能將資料新增在list 的結尾 格式: `append(`你要插入的資料`)` ```python= e = list() #同 e = [] e.append(3.27) e.append('x') print(e) #輸出[3.27, 'x'] ``` --- ### 2.`insert(int,object)` `insert()` 能將元素插入指定位置 格式: `insert(`你要插入的index`,`你要插入的元素`)` ```python= e = [6, 'x', 9, 'y'] e.insert(2,True) print(e) #輸出: [6, 'x', True, 9, 'y'] ``` --- ## `dict` 新增元素 `dict` 中新增元素需要搭配鍵值(key/index)新增,方法有兩種 ```python= d = dict() #同 d = {} #方法1: 取想新增的索引值後賦值,常用 d['d'] = 105 #方法2: 運用setdefault()成對塞進去,限鍵值不存在時使用 d.setdefault('x', True) print(d) #輸出: {'d': 105, 'x': True} ``` --- ### `setdefault()` 延伸 ```python= d = dict() # setdefault() 常用來新增 list 或 set 後進行操作 d.setdefault('e',[4.2]).append(3.27) d.setdefault('s',{7.1}).add(105)# set 新增元素用 add() print(d) #輸出: {'e': [4.2, 3.27], 's': {105, 7.1}} test = d.setdefault('e') #有了鍵值之後後面打啥都沒用 print(test) # 看看這是什麼 #輸出: [4.2, 3.27] print(d['e']) # 再看看這是什麼 #輸出: [4.2, 3.27] ``` --- ::: spoiler 練習 ```python= d['a'].insert(1,'C') d['a'].append('U') d['b'] = 'IT' #或 d.setdefault('b','IT') ``` --- ::: 不使用 元素變換,試將 `d` 透過 新增元素 變成 `dd`。 ```python= d = {'a':['N','H']} #新增元素 dd = {'a':['N','C','H','U'], 'b':'IT'} print(d,'' if(d == dd) else 'Wrong answer') ``` --- ## 移除元素 ### 1.`remove(object)` 使用 `remove()` 可以移除 `list` 中的指定資料 格式: `remove(`你要移除的資料`)` ```python= e = ['0',1,'2',3] e.remove('0') e.remove(1) print(e) #輸出: ['2', 3] ``` 注意 : `remove()` 適用 `list, set`, 另 `dict` 無法移除指定資料 --- ### 2.`pop(int/str)` `pop()` 可以根據輸入的 index 位置來移除元素 格式: `pop(`想移除元素的索引值/鍵值`)` ```python= e = ['a',1,'2',3] e.pop(2) print(e) #輸出: ['a', 1, 3] e.pop() #list 中如果空白的話則會移除最後一個 print(e) #輸出: ['a', 1] ``` --- 另外 `pop()` 是能回傳值的,如 ```python= e = ['x',1,'2',3] return_pop = e.pop(0) print(return_pop) #輸出: x ``` --- ::: spoiler 練習 ```python= d['a'].pop() #或 pop(3) 或 remove('U') d['a'].pop(1) #或 remove('C') d.pop('b') ``` --- ::: 不使用 元素變換,試將 `d` 透過 移除元素 變成 `dd`。 ```python= d = {'a':['N','C','H','U'], 'b':'IT'} #移除元素 dd = {'a':['N','H']} print(d,'' if(d == dd) else 'Wrong answer') ``` --- ## 先這樣 祝各位期中 All Pass~ --- ## 用途 JSON ```python=! d={ 'PlayName':'Mandy', 'BagItem':{ 'sword':{ 'LV':5, 'atk':2 }, 'hat':{ 'LV':10, 'def':3 } }, 'Equipment':{ 'GM hat':{ 'LV':1, 'def':999 }, 'GM Gun':{ 'LV':1, 'atk':999 } } } ``` --- ## 補充上次和這次的(有點底層,慎入) 早學晚學還是得學 > All data in a Python program is represented by objects or by relations between objects. 首先,python在宣告變數時是建立一個"參考" ```python= a=10 ``` python 中會為 a 建立一個參考,並且參考至 物件 <int> 然後 int 的 value = 10 並且每個物件被建立之初便擁有了自己的 id (refrence 位置) 舉例 ```python= a=[10] b=a print(a,b) a[0]+=100 print(a,b) ``` 原理: (以下稱 範例中的那個list 為the_list) a 參考至 the_list b=a 所以 b 也會參考至 the_list 又the_list[0] 在一開始參考至 10 所以我們在更動a[0] 的時候就是讓the_list[0] 參考至 110 ![](https://i.imgur.com/EFugcxk.png) 如果想知道更詳細請使用" id() "自己印出對應的id來檢驗 ex ```python= a=10 print(id(a)) ``` [詳見](https://docs.python.org/3/reference/datamodel.html#objects-values-and-types) ### is 與 == 的區別 == 是對 value 做比較 is 則是檢查 id ```python= a=10 b=[100/10] print(a == b[0]) print(a is b[0]) ``` 試試看ㄅ~ ## leetcode https://leetcode.com/problems/linked-list-cycle/ https://leetcode.com/problems/reverse-linked-list/ <style>hr{display:none;}</style>

    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