Site icon George的生活點滴

python List 陣列

Python 的 『陣列』有幾種形式:
List 這與其它程式的 array 很類似:
my_list=[‘hello’,’world’] ,此時我們有一個名為 my_list 的 List,其值有二: hello 與 world,List 的值放在中括號 [ ]中  (square brackets )。
List 的相關操作有:
append()    增加列表元素  my_list.append(‘george’),my_list 會變為 [‘hello’,’world’,’george’] 。
insert(y,x)  增加列表元素,把 x 放在 List 中 y 的位置  my_list.insert( 2,’,’),my_list 會變為 [‘hello’,’world’,’,’,’george’] 。
remove(‘,’) 刪除 List 中 ‘,’ 的值,my_list.remove(‘,’),my_list 會變為 [‘hello’,’world’,’george’] 。
pop ()      顯示最後一個數據並刪除 my_list. pop () ,會顯示  george 並刪除,my_list 會變為 [‘hello’,’world’]。
count()    顯示 () 中數值在 List 中出現的次數  my_list.count(‘hello’) 會顯示 1,代表一次。
index()    顯示 () 中數值在 List 中的位置  my_list.index(‘hello’) 會顯示 0,表示 hello 在 List 中的第 0 位。
reverse() 將 List 反轉, my_list.reverse() 後 List 會變成  [‘world’,’hello’]。
sort()      排序 List,my_list.sort() 後會變為  [‘hello’,’world’],預設由小到大排序,若需反向排序要寫成 my_list.sort(reverse=True) 。

Exit mobile version