也許和大多數普通人一樣,我經歷了一個特別的2020年,手足無措,渾渾噩噩,整頓修養,
終于2021年萬物復蘇的春天,我把自己支楞了起來,重新開始學習和記錄,第一步打算系統整理或者說復習 Python,以前因為作業斷斷續續地學習,自己了解的知識都是七零八落的,寫起代碼就是東拼西湊的,
希望這次的復習能得個全貌,
List
list 是容器資料型別(collection)的其中一種,它允許在一個變數中存放多個數值,
List Constants
list 可以存放任意 Python 資料型別,例如 number,string,character,甚至是 list,
list = [] #empty list
list = [1, 2, 3, 4]
list = ['a', 'b', 'c', 'd']
list = ["apple", "banana", "cat", "dog"]
list = [1, [2, 3], 4]
與 string 類似,list 也可以利用 indexing 獲取 list 中某個值,如:
list = [1, 2, 3, 4]
print(list[2])
>> 3
但是和 string 不一樣的是, list 的值是可以修改的,而 string 的值是不可以修改的,
list = ['a', 'p', 'p', 'l', 'e']
list[2] = 'x'
print(list)
>> ['a', 'p', 'x', 'l', 'e']
List Manipulating
對連接或者分割 list,有兩個重要的符號,分別是 “+” 和 “:”,
“+” 是用于連接兩個 list, 如:
a = [1, 2]
b = [3, 4]
list = a + b
print(list)
>> [1, 2, 3, 4]
“:” 是用于分割 list的, 如:
list = [1, 2, 3, 4, 5]
sublist = list[1:3] #from index = 1 to index = 3-1
print(sublist)
>> [2, 3]
sublist = list[:3] #from index = 0 to index = 3-1
print(sublist)
>> [1, 2, 3]
sublist = list[1:] #from index = 1 to index = len(list) -1
print(sublist)
>> [2, 3, 4, 5]
List Methods
列舉幾個常用的 methods.
- append:增加新的值
- in:檢查 list 是否包含某個值
list = [1, 2, 3, 4]
print(9 in list)
>> False
- sort:對 list 的值進行排序
- len:計算 list 的長度
- max,min,sum:計算 list 的最大值,最小值以及總和
List and Loop
如果需要遍歷 list 中的每一個值也很簡單,我們可以利用 for:
list = [1, 2, 3, 4, 5]
for ii in list:
print(ii)
也可以利用 for 和 range() 遍歷 list 中的 index,從而獲取 list 的值:
list = [1, 2, 3, 4, 5]
for ii in range(len(list)):
print(list[ii])
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/262365.html
標籤:Python
上一篇:Python的回圈結構,也簡單!
