Danh sách

Nhập môn Python dành cho Developer

Jasmin Ludolf

Senior Data Science Content Developer

Vấn đề

# Biến tên nguyên liệu
ingredient_one = "pasta"
ingredient_two = "tomatoes"
ingredient_three = "garlic"
ingredient_four = "basil"
ingredient_five = "olive oil"
ingredient_six = "salt"
Nhập môn Python dành cho Developer

Danh sách cứu nguy!

  • List = lưu nhiều giá trị trong một biến
    • Có thể chứa mọi kiểu dữ liệu kết hợp

 

# Danh sách nguyên liệu
ingredients = ["pasta", "tomatoes", "garlic", "basil", "olive oil", "salt"]
# Danh sách nguyên liệu dùng biến làm giá trị
ingredients = [ingredient_one, ingredient_two, ingredient_three,
               ingredient_four, ingredient_five, ingredient_six]
Nhập môn Python dành cho Developer

Kiểm tra kiểu dữ liệu

# Kiểm tra kiểu dữ liệu của danh sách
print(type(ingredients))
<class 'list'>
Nhập môn Python dành cho Developer

Truy cập phần tử của danh sách

# In mọi giá trị trong biến danh sách
print(ingredients)
['pasta', 'tomatoes', 'garlic', 'basil', 'olive oil', 'salt']
  • Danh sách có thứ tự và đánh chỉ mục
    • Python gán chỉ số bắt đầu từ 0 cho phần tử đầu
Nhập môn Python dành cho Developer

Truy cập phần tử của danh sách

  • List = []
  • Truy cập phần tử = a_list[index]
ingredients = ["pasta", "tomatoes",
"garlic", "basil", "olive oil", "salt"]

# Lấy giá trị tại chỉ số đầu tiên
print(ingredients[0])
pasta
# Lấy phần tử thứ tư
print(ingredients[3])
basil
Nhập môn Python dành cho Developer

Tìm phần tử cuối trong danh sách

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

# Lấy phần tử cuối của danh sách
print(ingredients[5])
salt
# Lấy phần tử cuối của danh sách
print(ingredients[-1])
salt
Nhập môn Python dành cho Developer

Truy cập nhiều phần tử

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

# Truy cập phần tử thứ hai và thứ ba
print(ingredients[1:3])
["tomatoes", "garlic"]
  • [first_element:last_element + 1]
  • Cộng một vào chỉ số cuối vì:
    • Python trả về mọi thứ đến nhưng không gồm chỉ số đó
Nhập môn Python dành cho Developer

Truy cập nhiều phần tử

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

# Truy cập tất cả phần tử từ chỉ số 3 trở đi
print(ingredients[3:])
['basil', 'olive oil', 'salt']
# Lấy ba phần tử đầu tiên
print(ingredients[:3])
['pasta', 'tomatoes', 'garlic']
Nhập môn Python dành cho Developer

Truy cập xen kẽ

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

# Truy cập mỗi phần tử thứ hai print(ingredients[::2])
['pasta', 'garlic', 'olive oil']]
  • Trả về các phần tử ở chỉ số 0, 2, 4
# Truy cập mỗi phần tử thứ ba, bắt đầu tại phần tử thứ hai
print(ingredients[1::3])
['tomatoes', 'olive oil']
  • Trả về các phần tử ở chỉ số 1 và 4
Nhập môn Python dành cho Developer

Ayo berlatih!

Nhập môn Python dành cho Developer

Preparing Video For Download...