今天的影片內容為介紹在Python中常用來儲存資料的形式,分別是串列(list)、元祖(tuple)與字典(dictionary),以及各自的使用說明
對了!領隊在錄影片時健忘症突然發作,到剪完片才發現忘記介紹某個重要的功能...
播到片尾時先別急著離開,後面還有呦~
以下為影片中有使用到的程式碼
#串列
list_1 = [12,12.0,"Jellyfish",[1,2,3]]
print(list_1)
#列印串列中的元素
list_2 = [25,39,46,85,[2,3],86]
print(list_2[0])
print(list_2[3])
print(list_2[-3])
print(list_2[-1])
print(list_2[4][0])
print(list_2[4][1])
#修改串列元素
list_3 = [11,12,13,14,15]
print(list_3)
list_3[1] = 1000
print(list_3)
#在串列尾端增加元素
list_4 = [1,2,3,4,5,6]
print(list_4)
list_4.append(7)
print(list_4)
#串列複製會出現的問題
a = 100
b = a
print(a,b)
b = b + 100
print(a,b)
before = [1,2,3,4,5,6,7]
after = before
print(before)
print(after)
after[0] = 100
print(before)
print(after)
#解決方法
import copy
before = [1,2,3,4,5,6,7]
after = copy.deepcopy(before)
print(before)
print(after)
after[0] = 100
print(before)
print(after)
#元組
tup_1 = (12,12.0,"Jellyfish",[1,2,3])
print(tup_1)
print(tup_1[1])
print(tup_1[3])
print(tup_1[3][0])
tup_1[1] = 100
print(tup_1)
#字典
dict_1 = {'animals':'Jellyfish','kg':20,'number':[0,1,0,1,2]}
print(dict_1)
#列印字典中所有key
print(dict_1.keys())
#列印字典中所有value
print(dict_1.values())
#增加key與value
dict_1['age'] = 1
print(dict_1)
#搜尋
print(dict_1['animals'])
print(dict_1['kg'])
print(dict_1['number'])
如果在影片中有說得不太清楚或錯誤的地方,歡迎留言告訴我,謝謝您的指教。