2017年9月29日 星期五

Python - List筆記

宣告方式
a = []

串列List內容值可接受多種不同的型別
a = [1,2,"3",4.5,['a','b','c','d']]

舉例,除非另外宣告a串列,大部份範例都由以下a串列起始
a = [1,2,3,4,5]

使用len()存取陣列長度
print(len(a)) # 5 

串列可以利用索引值讀取值
print(a[2]) # 3

索引值可以為負值
a[-1] # 等同a[4] display 5

同樣也可以像字串擷取資料
a[2:] # [3, 4, 5]

利用append加入值至串列結尾
a.append(6);
print(a) # [1, 2, 3, 4, 5, 6]

結合不同的串列利用extend(),結合後b會結合在結尾
b = [6, 7, 8]
a.extend(b) 
print(a) # [1, 2, 3, 4, 5, 6, 7, 8]
補充:extend()也等同於+=

利用pop()彈出串列中的值
a.pop()
print(a) # [1, 2, 3, 4] 5被彈出,因為沒有參數預設彈出最後一個值
pop()也可以搭配索引值參數使用
a.pop(0)
print(a) # [2, 3, 4, 5] 1被彈出

利用insert()插入串列,新增在指定索引值裡,其餘的值索引值往後推
a.insert(2,"new")
print(a) # [1, 2, 'new', 3, 4, 5, 6]

利用reverse()顛倒串列
a.reverse()
print(a) # [5, 4, 3, 2, 1]

利用sort()排序串列值,使用sorted()將不會改變內容值而是更改於建立的副本中
b = [3,5,1,3,7,6,4,55,99]
b.sort()
print(b) # [1, 3, 3, 4, 5, 6, 7, 55, 99]

巢狀陣列讀取方式,二維串列為例
c = [['a','b','c'],['A','B','C']]
print(c[0][2]) # c

利用for迭代串列
matrix = [[1,2,3],[4,5,6],[7,8,9]]
first_col = [row[0] for row in matirx]
print(first_col) # [1,4,7]

利用tuple()轉成Tuple
print(tuple(a)) # (1, 2, 3, 4, 5)

利用set()轉成Set
a = [1, 1, 1, 2, 3, 3]
print(set(a)) # set([1, 2, 3])

利用index()尋找索引值
a.index('3') # 2

利用count()找出特定字串元出現次數
a.count('2') # 1








沒有留言:

張貼留言