Python-串列list === ###### tags: `python` > [name=Ice] > [time=Fri, Oct 28, 2022 3:58 PM] ## 串列建立 ### 中括號包住值 ```python= a = ['zero', 'one', 'two'] print(a) #['zero', 'one', 'two'] ``` ### 使用for loop輸入大量值 ```python= a = [i for i in range(0,10)] print(a) #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] a = [1 for i in range(0,10)] print(a) #[1, 1, 1, 1, 1, 1, 1, 1, 1, 1] ``` ### 拆字串轉串列 list() ```python= a='cute' a=list(a) print(a) #['c', 'u', 't', 'e'] ``` ### 切割split() ```python= a = 'Ice is so cute' print(a.split(" ")) #['Ice', 'is', 'so', 'cute'] ``` ## List Method ### **len()** List長度 查詢list長度 ```python= a = [1, 2, 3] print(len(a)) #3 ``` ### **append()** 增加元素 末端增加元素 ```python= a = ['a', 'b', 'c'] a.append('d') print(a) #['a', 'b', 'c', 'd'] ``` ### **insert()** 增加元素 在指定位置加上元素(後面元素往後擠) ```python= a = ['a', 'b', 'c'] a.insert(1,'HELLO!') print(a) #['a', 'HELLO!', 'b', 'c'] ``` 這裡要再提醒!list首項位址是第0位! ### **extend()** List+List 將list加入list ```python= a = [1, 2, 3] b = [4, 5 ,6] a.extend(b) print(a) #[1, 2, 3, 4, 5, 6] ``` 在python內,也可以將list+list ```python= a = [1, 2, 3] b = [4, 5 ,6] c = a + b print(c) #[1, 2, 3, 4, 5, 6] ``` ### **remove()** 刪除元素 刪除指定元素 ```python= a = ['a', 'j', 'b', 'c'] a.remove('j') print(a) #['a', 'b', 'c'] ``` ### **del** 刪除元素 刪除指定位址元素 ```python= a = ['a', 'j', 'b', 'c'] del a[1] print(a) #['a', 'b', 'c'] ``` 刪除連續位址元素 ```python= a = ['a', 'j', 'b', 'c'] del a[1:3] print(a) #['a', 'c'] ``` 刪除所有元素 ```python= a = ['a', 'j', 'b', 'c'] del a[:] print(a) #[] ``` ### **pop()** 取出並刪除元素 取出指定位址且在list中刪除 ```python= #指定位址 a = ['a', 'b', 'c', 'd' ,'e'] b = a.pop(3) print(a) #['a', 'b', 'c', 'e'] print(b) #d ``` 若不指定位址,則取出且刪除最後一項 ```python= #不指定 a = ['a', 'b', 'c', 'd' ,'e'] b = a.pop() print(a) #['a', 'b', 'c', 'd'] print(b) #e ``` ### **clear()** 清空List 清空串列 ```python= a = [1, 2, 3] a.clear() print(a)#[] ``` ### **index()** 查詢位址 查詢元素位址 ```python= a = ['a', 'b', 'c'] print(a.index('c')) #2 ``` ### **count()** 計算元素數量 計算指定元素數量 ```python= a = [1, 2, 3, 2, 2, 3, 5] print(a.count(2)) #3 print(a.count(5)) #1 ``` ### **sort()** 排列 - reverse=False : 小到大排列 - reverse=True : 大到小排列 ```python= a = [1, 5, 3, 6, 2, 9, 4] a.sort(reverse=True) print(a) #[9, 6, 5, 4, 3, 2, 1] #字母也可以排列 b = ['a','c','d','b'] b.sort(reverse=False) print(b) #['a', 'b', 'c', 'd'] ``` ### **reverse()** 反轉 反轉list ```python= a =[1, 3, 5, 6, 7, 9] a.reverse() print(a) #[9, 7, 6, 5, 3, 1] ```