8 資料容器二

8.1 set

set 是一個存放唯一值(unique values)的資料容器,當我們希望可以移除重複的資料時,set 就可以派上用場。

8.1.1 建立 set

我們可以使用 set() 函數將既有的 list 轉換成為 set,或者在建立物件的時候使用大括號 {} 藉此區別建立 list 時候所使用的中括號 []

# 使用 set 函數
gender_list = ["female", "female", "female", "male", "male", "male"]
gender_set = set(gender_list)
print(gender_set)
## set(['male', 'female'])
print(type(gender_set))
## <type 'set'>
# 使用大括號建立
gender_set = {"female", "female", "female", "male", "male", "male"}
print(gender_set)
## set(['male', 'female'])
print(type(gender_set))
## <type 'set'>

8.1.2 set 無法選出裡面的元素

set 與 list 和 tuple 最大的不同點在於它沒有辦法利用中括號與索引值選取元素。

gender_set = {"female", "female", "female", "male", "male", "male"}
print(gender_set[0])

8.2 dict

dict 是帶有鍵值(key)的 list。

8.2.1 建立 dict

在建立的 dict 時候我們需要使用大括號 {} 並且指派每一個資料的鍵值。

friends_dict = {
    "genre": "sitcom",
    "seasons": 10,
    "episodes": 236,
    "starrings": ["Jennifer Aniston", "Courteney Cox", "Lisa Kudrow", "Matt LeBlanc", "Matthew Perry", "David Schwimmer"]
}
print(type(friends_dict))

8.2.2 利用鍵值選出 dict 中的元素

我們在中括號 [] 中使用鍵值來選擇元素。

friends_dict = {
    "genre": "sitcom",
    "seasons": 10,
    "episodes": 236,
    "starrings": ["Jennifer Aniston", "Courteney Cox", "Lisa Kudrow", "Matt LeBlanc", "Matthew Perry", "David Schwimmer"]
}
print(friends_dict["genre"])
print(friends_dict["seasons"])
print(friends_dict["episodes"])
print(friends_dict["starrings"])

8.2.3 dict 與 for 迴圈

dict 的結構比 list 多了鍵值(key),如果沒有特別指定,迴圈輸出的會是 dict 的鍵值。

starrings = {
    "Rachel Green": "Jennifer Aniston",
    "Monica Geller": "Courteney Cox",
    "Phoebe Buffay": "Lisa Kudrow",
    "Joey Tribbiani": "Matt LeBlanc",
    "Chandler Bing": "Matthew Perry",
    "Ross Geller": "David Schwimmer"
}
for starring in starrings:
    print starring
## Phoebe Buffay
## Joey Tribbiani
## Ross Geller
## Rachel Green
## Monica Geller
## Chandler Bing

比較清楚的寫法是在 dict 後面加入 .keys().values() 表示針對鍵值或內容進行迴圈的輸出。

starrings = {
    "Rachel Green": "Jennifer Aniston",
    "Monica Geller": "Courteney Cox",
    "Phoebe Buffay": "Lisa Kudrow",
    "Joey Tribbiani": "Matt LeBlanc",
    "Chandler Bing": "Matthew Perry",
    "Ross Geller": "David Schwimmer"
}
for starring in starrings.keys():
    print starring
## Phoebe Buffay
## Joey Tribbiani
## Ross Geller
## Rachel Green
## Monica Geller
## Chandler Bing
print("---")
## ---
for starring in starrings.values():
    print starring
## Lisa Kudrow
## Matt LeBlanc
## David Schwimmer
## Jennifer Aniston
## Courteney Cox
## Matthew Perry

如果希望同時將 dict 的鍵值與內容一起輸出,我們可以藉助 .items()

starrings = {
    "Rachel Green": "Jennifer Aniston",
    "Monica Geller": "Courteney Cox",
    "Phoebe Buffay": "Lisa Kudrow",
    "Joey Tribbiani": "Matt LeBlanc",
    "Chandler Bing": "Matthew Perry",
    "Ross Geller": "David Schwimmer"
}

for (key, value) in starrings.items():
    print("{}{} 演出".format(key, value))