Pythob 可以針對Iterable(可疊代的)物件來進行讀取,Python內建幾個常用的Iterable物件,像是String(字串)、List(串列)、Tuples(元組)、Dictionary(字典)等
for item in dict:
item
在語法中,in 的後方就是for-loop要讀取的目標物,這個目標物的為Iterable (可疊代的物件 String(字串)、List(串列)、Tuples(元組)、Dictionary(字典)),一次讀取一個元素,然後用item(自訂變數名稱)來接收每次讀取到的元素,執行區塊中的運算,如輸出
Python 的 Key 和 Value 用法 是用在 字典上
d = {key1: value1, key2: value2}
key 的資料型別沒有太多的限制,可以是 string (字串)、數字等等。
movie_1 = {'name': 'Saving Private Ryan',
'year': 1998,
'director': 'Steven Spielberg'}
name year director 都是 Key
for key in dict: print(key) for key, value in dict.items(): print(key, value)
dict_s = {}
for i in range(6):
dict_s[i] = i**3
print(dict_s)
相同結果
dict_s = {i: i**3 for i in range(6)}
print(dict_s)
my_s = {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
for i in my_s:
print("Key is", i, "Value is", my_s[i])
ANS
Key is 0 Value is 0
Key is 1 Value is 1
Key is 2 Value is 4
Key is 3 Value is 9
Key is 4 Value is 16
Key is 5 Value is 25
新北市國中 111年資訊科技
my_s = dict()
for i in range(5):
my_s[i]=2*i+1
print([key+value for key, value in my_s.items()])
ANS
[1, 4, 7, 10, 13]
my_s = dict()
for i in range(5):
my_s[i]=2*i+1
print(sum([key+value for key, value in my_s.items()]))
ANS
35