Python เบื้องต้นสำหรับนักพัฒนา
Jasmin Ludolf
Senior Data Science Content Developer
เก็บข้อมูลที่ไม่ซ้ำกัน
ไม่สามารถเปลี่ยนแปลงค่าได้
เหมาะสำหรับการระบุและลบข้อมูลซ้ำ
ค้นหาได้รวดเร็ว (เมื่อเทียบกับโครงสร้างข้อมูลอื่น เช่น 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() จะคืนค่าเป็น 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
Python เบื้องต้นสำหรับนักพัฒนา