導論與清單

Python 的資料型別

Jason Myers

Instructor

資料型別

  • 資料型別系統決定語言能做什麼
  • 了解資料型別能讓你更有掌控力
Python 的資料型別

容器序列

  • 可容納其他型別的資料
  • 用於聚合、排序等操作
  • 可變(listset)或不可變(tuple
  • 可迭代
Python 的資料型別

List(列表)

  • 依加入的順序保存資料
  • 可變
  • 可用索引存取
Python 的資料型別

存取單一項目

cookies = ['chocolate chip', 'peanut butter', 'sugar']
cookies.append('Tirggel')
print(cookies)
['chocolate chip', 'peanut butter', 'sugar', 'Tirggel']
print(cookies[2])
sugar
Python 的資料型別

合併清單

  • 使用運算子可把兩個 list 合併成新清單
cakes = ['strawberry', 'vanilla']

desserts = cookies + cakes

print(desserts)
['chocolate chip', 'peanut butter', 'sugar', 'Tirggel', 'strawberry', 'vanilla']
  • .extend() 方法會把一個清單的元素接到另一個清單尾端
cookies.extend(cakes)
Python 的資料型別

尋找清單元素

  • .index() 方法可找出元素在清單中的位置
position = cookies.index('sugar')

print(position)
3
Python 的資料型別

移除清單元素

  • .pop() 方法會移除清單中的項目,並讓你保存它
name = cookies.pop(position)

print(name)
sugar
print(cookies)
['chocolate chip', 'peanut butter', 'Tirggel']
Python 的資料型別

迭代清單

  • List comprehension 常用來迭代清單並對元素進行操作
titlecase_cookies = [cookie.title() for cookie in cookies]
print(titlecase_cookies)
Chocolate Chip
Peanut Butter
Tirggel
Python 的資料型別

排序清單

  • sorted() 函式依數值或字母順序排序,並回傳新清單
print(cookies)
['chocolate chip', 'peanut butter', 'Tirggel']
sorted_cookies = sorted(cookies)

print(sorted_cookies)
['Tirggel', 'chocolate chip', 'peanut butter']
Python 的資料型別

一起來練習吧!

Python 的資料型別

Preparing Video For Download...