###### [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>
{"metaMigratedAt":"2023-06-15T14:01:13.882Z","metaMigratedFrom":"YAML","breaks":true,"description":"中興大學資訊研究社1091學期程式分享會主題社課","title":"容器","contributors":"[{\"id\":\"6d6e3ba2-6820-4c6f-9117-f09bccc7f7aa\",\"add\":0,\"del\":29},{\"id\":\"e86b6571-4dea-4aa4-ba20-ece559b0e015\",\"add\":18353,\"del\":12096},{\"id\":\"4c23290c-4304-45d6-9c21-163639f3ac69\",\"add\":1147,\"del\":304}]"}
    922 views
   owned this note