Try   HackMD

第五堂 python四大基本型態、結構

List 陣列、串列

list是有序的

string = "String" for s in string: print(s) # "String" => "S","t","r","i","n","g"

Tuple 元組

tuple是有序的

跟list很像,但差別在於 初始值不能改變

初始化方法 Tuple

t1 = tuple() t2 = () print(t1) print(t2)

初始值給了之後不能再修改

t = (1,2,3) t[0] = 5

Dict 字典

一個對應一個,Key對應到Value
像字典一樣,一個名詞對應到一個解釋

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

d = { "a":"abc", "b":"bcd" } print(d) print(d['a']) print(d['b'])

要用到的東西一定要在字典內,否則會產生KeyError錯誤

d = { "a":"abc", "b":"bcd", "ab":"1231213", 5: "這是五" } print(d) print(d['ab']) print(d['a']) print(d['b']) print(d[5]) # 只會印出完全一樣的key(鍵)的值, # 會找完全一樣的Key來做對應 # dict的key中可以同時有數字、字串

dict是無序的,沒有前後順序

d = { "cat":"小貓", "dog":"小狗", "bird":"小鳥", "fish":"魚", } print(d['cat']) for i in d: print("key:", i, " value:", d[i])

Set 集合

set是無序的

Set跟Dict都是用大括號{},
特點在於,會把重複的東西自動去除

s = set() s = {1,2,3,1,2,3,"1","2","3"} print(s)

去除重複的資料

l = ["小明","小華","小東","小明"] print(l) print(set(l)) # 把list轉成set