Tập hợp và bộ

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

Jasmin Ludolf

Senior Data Science Content Developer

Tập hợp (set)

  • Chứa dữ liệu duy nhất

  • Không thay đổi

    • Có thể thêm hoặc xóa giá trị, nhưng không thể sửa chúng
  • Lý tưởng để nhận diện và loại bỏ trùng lặp

  • Tìm kiếm nhanh (so với cấu trúc dữ liệu khác như list)

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

Tạo một tập hợp

  • Set = {}
  • : = Dictionary
  • Không có : = Set
# Create a set of ingredients
ingredients = {"pasta", "tomatoes", "pasta", 
                 "basil", "garlic", "olive oil", "salt"}
print(ingredients)
{'pasta', 'tomatoes', 'garlic', 'basil', 'olive oil', 'salt'}
Nhập môn Python dành cho Developer

Chuyển đổi sang tập hợp

# Existing list variable
ingredients_list = ["pasta", "tomatoes", "garlic", "basil"
                    "olive oil", "pasta", "salt"]


# Convert to a set unique_ingredients = set(ingredients_list)
# Check the data type type(unique_ingredients)
set
Nhập môn Python dành cho Developer

Chuyển đổi sang tập hợp

print(unique_ingredients)
{'pasta', 'tomatoes', 'garlic', 'basil', 'olive oil'}
Nhập môn Python dành cho Developer

Hạn chế của tập hợp

  • Không có chỉ số
    • Không có phần tử trùng
    • Không thể truy cập bằng []
# Trying to subset a set
print(unique_ingredients[0])
TypeError: 'set' object is not subscriptable
Nhập môn Python dành cho Developer

Sắp xếp một tập hợp

ingredients = {"pasta", "tomatoes", "garlic", 
                 "basil", "olive oil", "salt"}


# Sorting a set print(sorted(ingredients))
['basil', 'garlic', 'olive oil', 'pasta', 'salt', 'tomatoes']
  • sorted() trả về một list
Nhập môn Python dành cho Developer

Bộ (tuple)

  • Bất biến - không thể thay đổi
    • Không thêm giá trị
    • Không xóa giá trị
    • Không sửa giá trị

 

  • Có thứ tự
    • Có thể truy cập theo chỉ số, ví dụ [0]

 

  • Hữu ích cho thông tin vị trí hoặc định danh

Ổ khóa trên laptop

1 https://unsplash.com/@towfiqu999999
Nhập môn Python dành cho Developer

Tạo một bộ

# Creating a tuple
serving_sizes = (1, 2, 4, 6, 8)


# Convert another data structure to a tuple ingredients_tuple = tuple(ingredients_list)
Nhập môn Python dành cho Developer

Truy cập bộ

# A tuple
serving_sizes = (1, 2, 4, 6, 8)

# Access the second element
print(serving_size[1])
2
Nhập môn Python dành cho Developer

Ayo berlatih!

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

Preparing Video For Download...