DAY 3
0

串列(List)

認識串列

``````# integer
list_1 = [1, 2, 3, 4, 5]
# string
list_2 = ['1', '2', '3']
# 來點混搭風如何？
list_3 = [1, '1', '1.0']
# 串列的串列的串列？
list_4 = [1, [1, [1]]]
# 串列也可以是空的
list_5 = []
``````

讀取串列

``````x = [1, 2, 3, 4, 5]
# 我要第一個數字
print(x[0])
# 我要最後一個數字
print(x[4])
``````

``````x = [1, 2, 3, 4, 5]
# 我要最後一個數字
print(x[-1])
``````

``````x = [1, 2, 3, 4, 5]
# 我要最後一個數字
print(x[len(x)-1])
``````

串列切片

``````x = [1, 2, 3, 4, 5]

# 取索引值前3，索引值是 0 1 2
x[:3]
>>> [1, 2, 3]

# 從索引值1開始到索引值4，索引值是1 2 3
x[1:4]
>>> [2, 3, 4]

# 取得串列最後第 n 個
x[-2:]
>>> [4, 5]

# 每隔 step 從 start 開始到 end-1
# [start:end:step]
x[1:4:2]
>>> [2, 4]
``````

搭配運算

``````# sum
x = [1, 2, 3, 4, 5]
sum(x)
>>> 15

# max
max(x)
>>> 5

# min
min(x)
>>> 1

``````

``````import numpy as np

x = [1, 2, 3, 4, 5]

# 中位數
np.median(x)
>>> 3.0

# 平均數
np.mean(x)
>>> 3.0

``````

增加或刪除元素

``````x = [1, 2, 3, 4, 5]
x.append(6)
print(x)
>>> [1, 2, 3, 4, 5, 6]
``````

``````x = [1, 2, 3, 4, 5]
x.insert(3, 6)
print(x)
>>> [1, 2, 3, 6, 4, 5]
``````

``````x = [1, 2, 3, 4, 5]
x.pop()
print(x)
>>> [1, 2, 3, 4]
``````

``````x = [1, 2, 3, 4, 5]
x.pop(3)
print(x)
>>> [1, 2, 3, 5]
``````

``````x = [1, 2, 3, 4, 5]
x.remove(3)
print(x)
>>> [1, 2, 4, 5]
``````

顛倒排序

``````x = [1, 2, 3, 4, 5]
print(x[::-1])
>>> [5, 4, 3, 2, 1]
``````
``````x = [1, 2, 3, 4, 5]
x.reverse()
print(x)
>>> [5, 4, 3, 2, 1]
``````

排序

``````x = [9, 4, 6, 10, 8]
x.sort()
print(x)
>>> [4, 6, 8, 9, 10]
``````

``````x = [9, 4, 6, 10, 8]
x.sort(reverse=True)
print(x)
>>> [10, 9, 8, 6, 4]
``````

``````x = [9, 4, 6, 10, 8]
y = sorted(x)
print('Before:', x)
print('After:', y)
>>> Before: [9, 4, 6, 10, 8]
>>> After: [4, 6, 8, 9, 10]
``````

字典(Dict)

``````dict_1 = {}
dict_2 = {"banana": 10, "apple": 20, "lemon": 30}
``````

回傳字典的值

``````fruit_price_dict = {"banana": 10, "apple": 20, "lemon": 30}
print(f"The price of banana is:", fruit_price_dict["banana"])
>>> The price of banana is: 10
``````

加上新的元素

``````fruit_price_dict = {"banana": 10, "apple": 20, "lemon": 30}
fruit_price_dict["orange"] = 50
print(fruit_price_dict)
>>> {'banana': 10, 'apple': 20, 'lemon': 30, 'orange': 50}
``````

更新 value

``````fruit_price_dict = {'banana': 10, 'apple': 20, 'lemon': 30, 'orange': 50}
fruit_price_dict["orange"] = 60
print(fruit_price_dict)
>>> {'banana': 10, 'apple': 20, 'lemon': 30, 'orange': 60}
``````

刪除指定元素

``````fruit_price_dict = {'banana': 10, 'apple': 20, 'lemon': 30, 'orange': 50}
del fruit_price_dict["orange"]
print(fruit_price_dict)
>>> {'banana': 10, 'apple': 20, 'lemon': 30}
``````

字串

切片處理

``````string = 'PythonGO!'
print(string[0])
>>> P
print(string[6:])
>>> GO!
``````

轉成字串

``````string = 'PythonGO!'
list(string)
>>> ['P', 'y', 't', 'h', 'o', 'n', 'G', 'O', '!']
``````

分隔處理

``````string = 'I want to play a game!'
string.split(' ')
>>> ['I', 'want', 'to', 'play', 'a', 'game!']
``````

合併處理

``````string = ['I', 'want', 'to', 'play', 'a', 'game!']
' '.join(string)
>>> 'I want to play a game!'
``````

Python資料分析學習地圖30