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)