3.python數據結構-集合(set)

# 集合(set)
# 無序、不重複、可放不同類型元素

# 創建非空集合,用{元素序列}
a_set = {1, 2, 'a', 'a', 2}
print('create a non-empty set:')
print(a_set)

# 創建空集合不能用{},{}爲空dict
a_set = set()
print('create a empty set:')
print(a_set)

# 初始化兩個句子
str_1 = 'dogs chase cats'
str_2 = 'dogs hate cats'

# 統計句子中不重複單詞的集合
str_1_words = set(str_1.split())
str_2_words = set(str_2.split())

# 集合不支持索引和切片
try:
    str_1_words[1]
except:
    print("Don't support index")  # Don't support index
try:
    str_1_words[1:]
except:
    print("Don't support slice")  # Don't support slice

# 計算兩個句子中不重複單詞的個數
len_str_1_words = len(str_1_words)
len_str_2_words = len(str_2_words)
print(len_str_1_words, len_str_2_words)  # output:3 3

# 計算兩個set的交集
print(str_1_words.intersection(str_2_words))  # output:{'dogs', 'cats'}
print(str_1_words & str_2_words)  # output:{'dogs', 'cats'}

# 計算兩個set的並集
print(str_1_words.union(str_2_words))  # output:{'hate', 'dogs', 'chase', 'cats'}
print(str_1_words | str_2_words)  # output:{'hate', 'dogs', 'chase', 'cats'}

# 計算差集
print(str_1_words.difference(str_2_words))  # output:{'chase'}
print(str_1_words - str_2_words)  # output:{'chase'}

# 計算異或關係
print(str_1_words.symmetric_difference(str_2_words))  # output:{'hate', 'chase'}
print(str_1_words ^ str_2_words)  # output:{'hate', 'chase'}

# # 集合的用法(與sklearn結合)
# union_set = str_1_words.union(str_2_words)
# a = [1 if w in str_1_words else 0 for w in union_set]
# b = [1 if w in str_2_words else 0 for w in union_set]
#
# print(a) # output:[0, 1, 1, 1]
# print(b) # output:[1, 1, 0, 1]
#
# print(jaccard_similarity_score(a,b))
發佈了47 篇原創文章 · 獲贊 4 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章