Python基础入门易错易混淆知识点汇总(四)创建集合、集合操作、集合推导式等知识点

一、集合

        1、创建集合

        使用set将其他类型数据转换为集合:
aSet = set(range(1,5)) # 范围
bSet = set([0,1,2,3,4]) # 列表
cSet = set((1,2,3,4)) # 元组
dSet = set({'a':1,'b':2,'c':3,'d':4}) # 字典
print(aSet)
print(bSet)
print(cSet)
print(dSet)
{1, 2, 3, 4}
{0, 1, 2, 3, 4}
{1, 2, 3, 4}
{'a', 'b', 'c', 'd'}

        2、集合操作

        并集、交集、差集各使用两种方法:

a_set = set([5, 6, 7, 8, 9, 10])
b_set = {0, 1, 2, 3, 4, 5}
print(a_set | b_set) # 并集
print(a_set.union(b_set))
print(a_set & b_set) # 交集
print(a_set.intersection(b_set))
print(a_set - b_set) # 差集
print(a_set.difference(b_set))
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
{5}
{5}
{6, 7, 8, 9, 10}
{6, 7, 8, 9, 10}

        issubset()判断一个集合是否为另一个集合的子集:

x = {1, 2, 3}
y = {1, 2, 4, 6}
z = {1, 2, 3, 4, 5}
print(x.issubset(y))  # 测试是否为子集
print(x < y)  # 比较集合大小/包含关系
print(x.issubset(z))
print(x < z)
False
False
True
True

        3、集合推导式

word = "I'm a boy, I'm a girl. When it is true, it is true. that are cats, the red is red."
word = word.replace(',', '').replace('.', '')
word = word.split()
setWord = set(word)
print("第一种方法:")
for i in setWord:
    count = word.count(i)
    print(i, '出现次数:', count)
print("第二种方法:")
dict = {}
for key in word:
    dict[key] = dict.get(key, 0) + 1
print(dict)
print("第三种方法:")
from collections import Counter
result = Counter(dict)
print(result)
print(result.most_common(3))
第一种方法:
true 出现次数: 2
a 出现次数: 2
cats 出现次数: 1
is 出现次数: 3
that 出现次数: 1
When 出现次数: 1
the 出现次数: 1
I'm 出现次数: 2
girl 出现次数: 1
are 出现次数: 1
boy 出现次数: 1
it 出现次数: 2
red 出现次数: 2
第二种方法:
{"I'm": 2, 'a': 2, 'boy': 1, 'girl': 1, 'When': 1, 'it': 2, 'is': 3, 'true': 2, 'that': 1, 'are': 1, 'cats': 1, 'the': 1, 'red': 2}
第三种方法:
Counter({'is': 3, "I'm": 2, 'a': 2, 'it': 2, 'true': 2, 'red': 2, 'boy': 1, 'girl': 1, 'When': 1, 'that': 1, 'are': 1, 'cats': 1, 'the': 1})
[('is', 3), ("I'm", 2), ('a', 2)]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值