方法與函式

Python 金融入門

Adina Howe

Professor

方法 vs. 函式

方法
  • 所有方法都是函式
  • 串列方法是 Python 內建函式的子集
函式
  • 並非所有函式都是方法
  • 用在物件上
    • prices.sort()
  • 需要物件作為輸入
    • type(prices)
Python 金融入門

串列方法:sort

  • 串列有多個內建方法可用來擷取與操作資料
  • 方法以 list.method() 存取

list.sort() 會將元素由小到大排序

prices = [238.11, 237.81, 238.91]

prices.sort()
print(prices)
[237.81, 238.11, 238.91]
Python 金融入門

使用 append、extend 新增到串列

list.append() 會把單一元素加入串列

months = ['January', 'February', 'March']

months.append('April')
print(months)
['January', 'February', 'March', 'April']

list.extend() 會把每個元素加入串列

months.extend(['May', 'June', 'July'])

print(months)
['January', 'February', 'March', 'April', 'May', 'June', 'July']
Python 金融入門

實用串列方法:index

list.index(x) 會回傳元素 x 首次出現的最小索引

months = ['January', 'February', 'March']
prices = [238.11, 237.81, 238.91]
months.index('February')
1
print(prices[1])
237.81
Python 金融入門

更多函式…

  • min(list):回傳最小元素

  • max(list):回傳最大元素

Python 金融入門

找出 CPI 最小的月份

months = ['January', 'February', 'March']
prices = [238.11, 237.81, 238.91]
# Identify min price
min_price = min(prices)

# Identify min price index min_index = prices.index(min_price)
# Identify the month with min price min_month = months[min_index] print(min_month)
February
Python 金融入門

一起來練習吧!

Python 金融入門

Preparing Video For Download...