set 函數

Python 基礎: set 函數,建立一個無順序不重複的元素資料集,可以計算資料集的交集、差集跟合集

set 函式

class set([iterable])

運算 公式 說明
交集 & x & y 找出 x 和 y 中的 相同元素
聯集 | x | y 找出 x 和 y 中的 所有元素
差集 - x - y 找出在 x 中,但不在 y 中的元素(只有 x 有的元素)
補集 ^ x ^ y 找出 x 和 y 中的 不同元素

set 字串

sport_1 = 'basketball'
sport_2 = 'baseball'

sport_1_set = set(sport_1)
sport_2_set = set(sport_2)

print('sport_1_set: ', sport_1_set)
print('sport_2_set: ', sport_2_set)

# sport_1_set:  {'a', 'k', 't', 'e', 'l', 'b', 's'}
# sport_2_set:  {'b', 'a', 'l', 'e', 's'}


# 交集
sport_1_2_set_intersection = sport_1_set & sport_2_set
print('sport_1_2_set_intersection: ', sport_1_2_set_intersection)

# sport_1_2_set_intersection:  {'a', 'e', 'l', 'b', 's'}


# 聯集
sport_1_2_set_union = sport_1_set | sport_2_set
print('sport_1_2_set_union: ', sport_1_2_set_union)

# sport_1_2_set_union:  {'a', 'k', 't', 'e', 'l', 'b', 's'}


# 差集
sport_1_2_set_subtraction = sport_1_set - sport_2_set
print('sport_1_2_set_subtraction: ', sport_1_2_set_subtraction)

# sport_1_2_set_subtraction:  {'k', 't'}

sport_2_1_set_subtraction = sport_2_set - sport_1_set
print('sport_2_1_set_subtraction: ', sport_2_1_set_subtraction)

# sport_2_1_set_subtraction:  set()

# 補集
sport_1_2_set_complement = sport_1_set ^ sport_2_set
print('sport_1_2_set_complement: ', sport_1_2_set_complement)

# sport_1_2_set_complement:  {'k', 't'}

set dict 字典

user_dict_1 = {
    "name": "KJ",
    "home": "Taiwan",
    "job": "Developer"
}

user_dict_2 = {
    "name": "KJ",
    "home": "Taiwan",
    "age": 18
}

user_dict_1_set = set(user_dict_1)
user_dict_2_set = set(user_dict_2)

print('user_dict_1_set: ', user_dict_1_set)
print('user_dict_2_set: ', user_dict_2_set)

# user_dict_1_set:  {'home', 'job', 'name'}
# user_dict_2_set:  {'home', 'age', 'name'}

# 交集
user_dict_1_2_set_intersection = user_dict_1_set & user_dict_2_set
print('user_dict_1_2_set_intersection: ', user_dict_1_2_set_intersection)

# user_dict_1_2_set_intersection:  {'home', 'name'}


# 聯集
user_dict_1_2_set_union = user_dict_1_set | user_dict_2_set
print('user_dict_1_2_set_union: ', user_dict_1_2_set_union)

# user_dict_1_2_set_union:  {'name', 'home', 'job', 'age'}

# 差集
user_dict_1_2_set_subtraction = user_dict_1_set - user_dict_2_set
print('user_dict_1_2_set_subtraction: ', user_dict_1_2_set_subtraction)

# user_dict_1_2_set_subtraction:  {'job'}

user_dict_2_1_set_subtraction = user_dict_2_set - user_dict_1_set
print('user_dict_2_1_set_subtraction: ', user_dict_2_1_set_subtraction)
# user_dict_2_1_set_subtraction:  {'age'}



# 補集
user_dict_1_2_set_complement = user_dict_1_set ^ user_dict_2_set
print('user_dict_1_2_set_complement: ', user_dict_1_2_set_complement)

參考資料