集合與元組

Python 入門(開發者向)

Jasmin Ludolf

Senior Data Science Content Developer

Sets

  • 只含唯一資料

  • 不可變

    • 可加入或移除值,但不能修改其內容
  • 適合識別並移除重複

  • 搜尋快(比清單等結構更快)

Python 入門(開發者向)

建立 set

  • Set = {}
  • : = 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'}
Python 入門(開發者向)

轉換成 set

# 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
Python 入門(開發者向)

轉換成 set

print(unique_ingredients)
{'pasta', 'tomatoes', 'garlic', 'basil', 'olive oil'}
Python 入門(開發者向)

set 的限制

  • 沒有索引
    • 不允許重複
    • 不能用 [] 取子集
# Trying to subset a set
print(unique_ingredients[0])
TypeError: 'set' object is not subscriptable
Python 入門(開發者向)

排序 set

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


# Sorting a set print(sorted(ingredients))
['basil', 'garlic', 'olive oil', 'pasta', 'salt', 'tomatoes']
  • sorted() 會回傳 list
Python 入門(開發者向)

Tuples

  • 不可變——不能被修改
    • 不能新增值
    • 不能移除值
    • 不能改變值

 

  • 有序
    • 可用索引取值,如 [0]

 

  • 適用於位置資訊或識別碼

筆電上的掛鎖

1 https://unsplash.com/@towfiqu999999
Python 入門(開發者向)

建立 tuple

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


# Convert another data structure to a tuple ingredients_tuple = tuple(ingredients_list)
Python 入門(開發者向)

存取 tuple

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

# Access the second element
print(serving_size[1])
2
Python 入門(開發者向)

一起來練習吧!

Python 入門(開發者向)

Preparing Video For Download...