Nhập môn Python dành cho Developer
Jasmin Ludolf
Senior Data Science Content Developer
Chứa dữ liệu duy nhất
Không thay đổi
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)
{}: = Dictionary: = Set# Create a set of ingredients
ingredients = {"pasta", "tomatoes", "pasta",
"basil", "garlic", "olive oil", "salt"}
print(ingredients)
{'pasta', 'tomatoes', 'garlic', 'basil', 'olive oil', 'salt'}
# 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
print(unique_ingredients)
{'pasta', 'tomatoes', 'garlic', 'basil', 'olive oil'}
[]# Trying to subset a set
print(unique_ingredients[0])
TypeError: 'set' object is not subscriptable
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
[0]

# Creating a tuple serving_sizes = (1, 2, 4, 6, 8)# Convert another data structure to a tuple ingredients_tuple = tuple(ingredients_list)
# 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