DAY 4
0

## 串列的操作與運用

``````students=["bonny","jack","rose"] # 建立一個students串列
for student in students : # 告知python從students串列中取出名字，並將取出的名字存到student變數內
print(student) # 印出student變數取到的名字
print("hello !") # 跳出迴圈並印出hello
``````

``````bonny
jack
rose
hello !
``````

``````for student in students :
``````

``````print(student) # 印出bonny
``````

``````for student in students :
``````

``````print(student) #印出jack
``````

## 使用range()函式建立數字串列

range()函式能輕鬆的產生一系列的數字

``````for number in range(1,7):
print(number)
``````

``````1
2
3
4
5
6
``````

``````odd_numbers=list(range(1,10,2))
print(odd_numbers)
``````

``````[1,3,5,7,9]
``````

## 擷取串列中的某部分

1.沒有指定第一個元素的索引足標則從0開始計算
2.沒有指定最後一個元素的索引足標則視為切到最後一位

``````colors=["red","orange","yellow","green","blue"]
print(colors[0:3]) # 印出索引足標0,1,2對應的元素
print(colors[1:4]) # 印出索引足標1,2,3對應的元素
print(colors[:2]) # 印出從索引足標0到1的元素
print(colors[2:]) # 印出從索引足標2到最後的元素
print(colors[-2:]) # 印出從索引足標-2(也就是倒數第二個)到最後的元素
``````

``````["red","orange","yellow"]
["orange","yellow","green"]
["red","orange"]
["yellow","green","blue"]
["green","blue"]
``````

## 切片的迴圈應用

• for迴圈印出切片的串列

``````colors=["red","orange","yellow","green","blue"]
for color in colors[1:3] : # 印出colors串列中索引足標1和2的元素
print(color)
``````

``````orange
yellow
``````
• 複製串列

``````my_pets=["dog","cat","bird"] # 建立一個my_pets串列
friend_pets=my_pets[:] # 將my_pets串列複製到friend_pets串列
print("My pets :")
print(my_pets) # 印出my_pets串列
print("Friend's pets :")
print(friend_pets) # 印出friend_pets串列
``````

``````My pets :
["dog","cat","bird"]
Friend's pets :
["dog","cat","bird"]
``````

``````my_pets=["dog","cat","bird"] # 建立一個my_pets串列
friend_pets=my_pets[:] # 將my_pets串列複製到friend_pets串列

my_pets.append("rabbit") # 新增一個元素到my_pets串列
friend_pets.append("turtle") # 新增一個元素到friend_pets串列
print("My pets :")
print(my_pets) # 印出my_pets串列
print("Friend's pets :")
print(friend_pets) # 印出friend_pets串列
``````

``````My pets :
["dog","cat","bird","rabbit"]
Friend's pets :
["dog","cat","bird","turtle"]
``````

## 甚麼是多元組 ?

• 定義多元組

``````birthday=("1224","0801","0617") # 定義一個多元組
print(birthday[0]) # 印出多元組第一個元素
``````

``````1224
``````
• 用迴圈拜訪多元組

``````birthday=("1224","0801","0617") # 定義一個多元組
for day in birthday : # 在birthday多元組中取得元素再存到day變數裡
print(day) # 印出變數存到的值
``````

``````1224
0801
0617
``````
• 如何更改多元組的值

``````numbers=(1,2,3) # 定義一個多元組
print("Original :")
for number in numbers : # 在numbers多元組中取得元素再存到number變數中
print(number) # 印出變數存到的值

numbers=(4,5,6) # 讓原本多元組(1,2,3)的值改為(4,5,6)
print("Modified :")
for number in numbers :
print(number)
``````

``````Original :
1
2
3
Modified :
4
5
6
``````

HackMD網址 :https://hackmd.io/ZPo67I8uRteSWF-G9Vdsow?both