列表

Python for Developers 入门

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 for Developers 入门

用列表解决!

  • 列表:在一个变量中存储多个值
    • 可包含任意数据类型组合

 

# 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 for Developers 入门

检查数据类型

# Check the data type of a list
print(type(ingredients))
<class 'list'>
Python for Developers 入门

访问列表元素

# Print all values in the list variable
print(ingredients)
['pasta', 'tomatoes', 'garlic', 'basil', 'olive oil', 'salt']
  • 列表是有序且有索引的
    • Python 为第一个元素分配的索引从0开始
Python for Developers 入门

访问列表元素

  • 列表=[]
  • 访问元素=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 for Developers 入门

获取列表最后一个元素

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 for Developers 入门

访问多个元素

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 for Developers 入门

访问多个元素

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 for Developers 入门

按步长访问

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 for Developers 入门

Passons à la pratique !

Python for Developers 入门

Preparing Video For Download...