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))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值