Lists

Python 入門(開發者向)

Jasmin Ludolf

Senior Data Science Content Developer

問題

# Variables of ingredient names
ingredient_one = "pasta"
ingredient_two = "tomatoes"
ingredient_three = "garlic"
ingredient_four = "basil"
ingredient_five = "olive oil"
ingredient_six = "salt"
Python 入門(開發者向)

用清單來解救!

  • List:在單一變數中存多個值
    • 可包含任意資料型別的組合

 

# List of ingredients
ingredients = ["pasta", "tomatoes", "garlic", "basil", "olive oil", "salt"]
# List of ingredients using variables as values
ingredients = [ingredient_one, ingredient_two, ingredient_three,
               ingredient_four, ingredient_five, ingredient_six]
Python 入門(開發者向)

檢查資料型別

# Check the data type of a list
print(type(ingredients))
<class 'list'>
Python 入門(開發者向)

存取清單元素

# Print all values in the list variable
print(ingredients)
['pasta', 'tomatoes', 'garlic', 'basil', 'olive oil', 'salt']
  • List 具順序與索引
    • Python 從開始給第一個元素編號
Python 入門(開發者向)

存取清單元素

  • List = []
  • 存取元素 = a_list[index]
ingredients = ["pasta", "tomatoes",
"garlic", "basil", "olive oil", "salt"]

# Get the value at the first index
print(ingredients[0])
pasta
# Get the fourth element
print(ingredients[3])
basil
Python 入門(開發者向)

取得最後一個元素

ingredients = ["pasta", "tomatoes", "garlic", "basil", "olive oil", "salt"]

# Get the last element of a list
print(ingredients[5])
salt
# Get the last element of a list
print(ingredients[-1])
salt
Python 入門(開發者向)

存取多個元素

ingredients = ["pasta", "tomatoes", "garlic", "basil", "olive oil", "salt"]

# Access the second and third elements
print(ingredients[1:3])
["tomatoes", "garlic"]
  • [first_element:last_element + 1]
  • 尾端索引要加 1,因為:
    • Python 回傳到該索引「之前」但不包含它
Python 入門(開發者向)

存取多個元素

ingredients = ["pasta", "tomatoes", "garlic", "basil", "olive oil", "salt"]

# Access all elements from the third index onwards
print(ingredients[3:])
['basil', 'olive oil', 'salt']
# Get the first three elements
print(ingredients[:3])
['pasta', 'tomatoes', 'garlic']
Python 入門(開發者向)

交替存取

ingredients = ["pasta", "tomatoes", "garlic", "basil", "olive oil", "salt"]

# Access every second element print(ingredients[::2])
['pasta', 'garlic', 'olive oil']]
  • 回傳索引 0、2、4 的項目
# Access every third element, starting at the second
print(ingredients[1::3])
['tomatoes', 'olive oil']
  • 回傳索引 1 與 4 的項目
Python 入門(開發者向)

一起來練習吧!

Python 入門(開發者向)

Preparing Video For Download...