--- tags: Python, 基礎學科 --- # 串列 1.list是Python 的資料集合之一,最主要的功用是在一堆資料集合中利用一個變數儲存一維可以新增元素,刪除,置換,清除,對資料進行排序,合併二組串列 2.list 本身也是個函數,可以將一串資料轉換成串列存放的方式 3.List Methods from https://www.w3schools.com/python/python_lists.asp >Python has a set of built-in methods that you can use on lists. > > Method Description > append() Adds an element at the end of the list > clear() Removes all the elements from the list > copy() Returns a copy of the list > count() Returns the number of elements with the specified value > extend() Add the elements of a list (or any iterable), to the end of the current list > index() Returns the index of the first element with the specified value > insert() Adds an element at the specified position > pop() Removes the element at the specified position > remove() Removes the item with the specified value > reverse() Reverses the order of the list > sort() Sorts the list ## 語法 CODE ``` lst=['A','B','C','D','E'] print(lst) ``` RESULT ['A', 'B', 'C', 'D', 'E'] 取出某一索引值的資料,特別需要注恴的事,Python list 的索引值由0開始,所以下列程式段會是印出C 由負值開始會是從最後一個元素開始計算 ``` lst=['A','B','C','D','E'] print(lst[2]) print(lst[-2]) ``` RESULT C D 錯誤範例: lst=['A','B','C','D','E'] print(lst[-20]) 直譯後會產生index out of range的異常,原因是只有 **IndexError: list index out of range** 取出某一個範圍的值 ``` lst=['A','B','C','D','E'] print(lst[2:4]) print(lst[:2]) print(lst[2:]) ``` RESULT ['C', 'D'] ['A', 'B'] ['C', 'D', 'E'] 直接用固定值替換串列的元素 ``` lst=['A','B','C','D','E'] lst[0]=0 print(lst[0:2]) ``` RESULT [0, 'B'] 用迴圈新增或逐步取值 ``` lst=[] for i in range(10): lst.append(i) print(lst) ``` RESULT [0] [0, 1] [0, 1, 2] [0, 1, 2, 3] [0, 1, 2, 3, 4] [0, 1, 2, 3, 4, 5] [0, 1, 2, 3, 4, 5, 6] [0, 1, 2, 3, 4, 5, 6, 7] [0, 1, 2, 3, 4, 5, 6, 7, 8] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 取值 ``` for j in lst: print(j) ``` RESULT 0 1 2 3 4 5 6 7 8 9 ### 多維串列 多維串列的用意是將串列資料引進欄和列的概念 a = [[1, 2, 3], [4, 5, 6]] ![2darray](https://i.imgur.com/a8KPJjK.jpg) print(a[0])#print a的第一維串列資料 print(a[1])#print a的第一維串列資料 print(a[0][2])#印出六個值的第0行,第2欄的值 結果會得到3 ### 多維串列 與迴圈 ![2darray and forloop compute](https://i.imgur.com/x4CQrDX.jpg) ``` a = [[1, 2, 3, 4], [5, 6,7,8]] s = 0 for i in range(len(a)): for j in range(len(a[i])): s += a[i][j] print(s) ```