人工智能(python)开发 —— 集合(set) 固定集合(frozenset)

        本章主要介绍了集合和固定集合的相关知识。

一、集合的概念

1、集合的定义

        集合是可变的容器
        集合内的数据对象都是唯一的(不能重复多次的)
        集合是无序的存储结构,集合中的数据没有先后顺序关系
        集合内的元素必须是不可变的对象
        集合是可迭代对象
        集合是相当于只有键没有值的字典(键则是集合的数据)

2、集合的构造(创建)函数

        set()  创建一个空的集合对象(不能用{}来创建空集合)
        set(iterable)  用可迭代对象创建一个新的集合

3、示例

        s = set()              # 空集合
        s = {1,2,3,4}        # 非空集合

        set("name hello")                   # {'m', 'n', 'e', 'o', ' ', 'a', 'h', 'l'}    去掉重复的字符
        set("ABCSBCB")                     # {'C', 'B', 'S', 'A'}
        s = set([1, 2, 3, 2])                 # s = {1,2,3}

        s = set({"name":"tarena","age":10})     # {'name', 'age'}    只保留了键(key)
        s = set({1:"一", 2:"二", 5:"五"})              # s={1,2,5}

        s = set(("ABC",123,True))                       # {True, 'ABC', 123}
        s = {True,None,"ABC",(1,2,3),3.14}         # {None, True, 'ABC', 3.14, (1, 2, 3)}

二、集合的运算

        交集, 并集, 补集, 子集,超集,对称补集
        &         |            -         <        >         ^

1、& 生成两个集合的交集

        s1 = {1, 2, 3}
        s2 = {2, 3, 4}
        s3 = s1 & s2          # s3 = {2, 3}

2、|  生成两个集合的并集

        s1 = {1, 2, 3}
        s2 = {2, 3, 4}
        s3 = s1 | s2          # s3 = {1, 2, 3, 4}

3、-  生成两个集合的补集

        s1 = {1, 2, 3}
        s2 = {2, 3, 4}
        s3 = s1 - s2  # s3 = {1} 生成属性s1但不属性 s3的所有元素的集合
        s4 = s2 - s1  # s4 = {4}

        说明:
                A - B 属于A 且不属于B
                B - A 属于B 且不属于A

4、^  对称补集

        s1 = {1, 2, 3}
        s2 = {2, 3, 4}
        s3 = s1 ^ s2          # s3 = {1, 4}

5、子集和超集

> 判断一个集合是另一个集合的超集
< 判断一个集合是另一个集合的子集
        s1 = {4, 5, 6}
        s2 = {4, 5}
        s1 > s2              # True  s1是s2的超集
        s2 < s1              # True  s2是s1的子集

6、== != 判断集合是否相同

        {1, 2, 3}  == {2, 3, 1}      # True
        {1, 2}  != {3, 4}               # True

7、<=  >= 判断包含,被包含关系

        in / not in 运算符
                in判断一个元素是否存在于集合中(同其它容器类型的in 相同)
                not in 与 in相反

三、集合和字典的优点

        in / not in运算符的查找速度快

四、集合的内建函数操作

        len(x), max(x), min(x), sum(x), any(x), all(x)

五、python3 中常的集合方法

方法意义
S.add(e)在集合中添加一个新的元素e;如果元素已经存在,则不添加
S.remove(e)从集合中删除一个元素,如果元素不存在于集合中,则会产生一个KeyError错误
S.discard(e)从集合S中移除一个元素e;
S.clear()清空集合内的所有元素
S.copy()将集合进行一次浅拷贝
S.pop()从集合S中删除一个随机元素;如果此集合为空,则引发KeyError异常
S.update(s2)用 S与s2得到的全集更新变量S
以下内容可以用运算符操作代替 
S.difference(s2)用S - s2 运算,返回存在于在S中,但不在s2中的所有元素的集合
S.difference_update(s2)等同于 S = S ^ s2
S.intersection(s2)等同于S & s2
S.intersection_update(s2)等同于S = S & s2
S.isdisjoint(s2)如果S与s2交集为空返回True,非空则返回False
S.issubset(s2)如果S与s2交集为非空返回True,空则返回False
S.issuperset(...)如果S为s2的子集返回True,否则返回False
S.symmetric_difference(s2)返回对称补集,等同于 S ^ s2
S.symmetric_difference_update(s2)用S 与 s2的对称补集更新 S
S.union(s2)生成 S 与 s2的全集

六、集合是可迭代对象

        用for语句可以得到集合中的全部数据元素

s = {1, "二", 3.14, "Four"}
for x in s:
    print(x)

七、集合推导式

        集合推导式是用可迭代对象生成集合的表达式

        语法:
                {表达式 for 变量 in 可迭代对象 [if 真值表达式]}
                注:[] 括起的部分代表可省略

        推导式内的 for 子句可以嵌套

八、固定集合 frozenset

1、定义
        固定集合是不可变的,无序的,含有唯一元素的集合
2、作用

        固定集合可以作为字典的键,也可以作为集合的值

3、创建空的固定集合

        fz = frozenset()

4、创建非空的固定集合

        frozenset(iterable)  用可迭代对象创建集合

fz = frozenset([2, 3, 5, 7])
5、固定集合的运算

        同set运算完全一致
                & 交集, | 并集, - 补集, ^ 对称补集,
                > >= < <= == !=
                in , not in

6、固定集合的方法

        相当于集合的全部方法去掉修改集合的方法

九、练习集

1、第一题

经理:曹操 刘备 周瑜;技术员:曹操 周瑜 张飞 赵云
用集合求:
1、既是经理也是技术员的人是谁?
2、是经理,但不是技术员的人都是谁?
3、是技术员,但不是经理的人都有谁?
4、张飞是经理吗?
5、身兼一职的人都有谁?
6、经理和技术员工有几人?

manager = {"曹操","刘备","周瑜"}
technician = {"曹操","周瑜","张飞","赵云"}
print("经理:",manager)
print("技术员",technician)
print("经理and技术员",manager & technician)
print("经理 不是技术员",manager - technician)
print("不是经理 技术员",technician - manager)
print("张飞是经理?","张飞" in manager)
print("身兼一职的人",manager ^ technician)
print("经理和技术员工有%d人",len(manager | technician))
2、第二题

写一个程序,任意输入一篇英文文章(可能有多行),当输入空行时结束输入
判断出现英文单词的种类数
     the world
     the dream

     (种类数是3)

英文文章可以复制附录1:Be Whole in Life(追求人生的完整)

L = []
while True:
    s = input("请输入: ")
    if not s:
        break
    L.append(s)

print("您输入了%d行文字" % len(L))
L2 = []
for s in L:
    for ch in "0123456789’():“”–.,":
        s = s.replace(ch, ' ')
    print("====> : ", s)
    L2.append(s)

print(L2)
words_set = set()          # 创建一个空集合,把所有词放进去
for s in L2:
    words = s.split()      # 把字符串分拆成字符串列表
    for w in words:
        words_set.add(w)   # 把所有单位加到集合内

print("单词个数:", len(words_set))
print(words_set)

附录1:Be Whole in Life(追求人生的完整)

Once a circle missed a wedge. The circle wanted to be whole, so it went around looking for its missing piece. But because it was incomplete and therefore could roll only very slowly, it admired the flowers along the way. It chatted with worms. It enjoyed the sunshine. It found lots of different pieces, but none of them fit. So it left them all by the side of the road and kept on searching. Then one day the circle found a piece that fit perfectly. It was so happy. Now it could be whole, with nothing missing. It incorporated the missing piece into itself and began to roll. Now that it was a perfect circle, it could roll very fast, too fast to notice flowers or talk to the worms. When it realized how different the world seemed when it rolled so quickly, it stopped, left its found piece by the side of the road and rolled slowly away.
The lesson of the story, I suggested, was that in some strange sense we are more whole when we are missing something. The man who has everything is in some ways a poor man. He will never know what it feels like to yearn, to hope, to nourish his soul with the dream of something better. He will never know the experience of having someone who loves him give him something he has always wanted or never had.
There is a wholeness about the person who has come to terms with his limitations, who has been brave enough to let go of his unrealistic dreams and not feel like a failure for doing so. There is a wholeness about the man or woman who has learned that he or she is strong enough to go through a tragedy and survive, she can lose someone and still feel like a complete person.
Life is not a trap set for us by God so that he can condemn us for failing. Life is not a spelling bee, where no matter how many words you’ve gotten right, you’re disqualified if you make one mistake. Life is more like a baseball season, where even the best team loses one third of its games and even the worst team has its days of brilliance. Our goal is to win more games than we lose. When we accept that imperfection is part of being human, and when we can continue rolling through life and appreciate it, we will have achieved a wholeness that others can only aspire to. That, I believe, is what God asks of us --- not “Be perfect”, not “Don’t even make a mistake”, but “Be whole”.
If we are brave enough to love, strong enough to forgive, generous enough to rejoice in another’s happiness, and wise enough to know there is enough love to go around for us all, then we can achieve a fulfillment that no other living creature will ever know

附录2:译文

从前有个圆圈,它丢失了一小段。它想变得完整,于是它到处寻找它所丢失的那部分。由于不完整,它只能滚的非常慢。在路上,它羡慕过花儿,它与虫子聊过天,它享受了阳光的照耀。它遇到过很多不同的小段,可是没有一个适合它。所以它把它们丢在路边,继续寻找。有一天,圆圈找到了可以与它完美结合的一小段,它非常高兴。它现在终于完整了,不缺任何东西了。它把丢失的那段装到自己身上,然后滚了起来。它现在是个完整的圆圈了,它可以滚的很快,,快到忽视了花儿,快到没有时间和虫子们说话。当它意识到由于它滚的太快,世界变得如此的不同时,它便停了下来,把找到的那段卸下丢在路边,慢慢地滚走了。
我想这个故事告诉我们,从某种奇怪的意义上说,当我们缺少什么东西时,我们反而是更完整的。一个拥有一切的人在某些方面也是个穷人,他永远不会知道什么是渴望、什么是期待;永远不知道用渴求更美好的东西来充实他的灵魂。他永远不会知道一个爱他的人送给他一样他所梦寐以求的东西时是怎样的一种感觉。
人生的完整性,在于接受自己的缺陷,勇敢地丢弃不切实际的幻想,并且不觉得这样做是失败的;人生的完整性,在于知道自己足够强大,可以承受人生的苦难,可以在失去一个人时仍然觉得自己是完整的。
生活并不是上帝为了谴责我们的缺陷而设下的陷阱。人生也不是一场拼字比赛,无论你拼出了多少单词,只要拼错了一个你就前功尽弃了。人生更像一个棒球赛季,最好的球队也会丢掉三分之一的比赛,而最差的球队也有辉煌的胜利。我们的目标是让打赢的比赛比输掉的比赛多。当我们接受了“不完整性”是人生的一部分时,当我们在人生之路上不断前进并且欣赏生命之美时,我们就获得了别人只能渴望的完整的人生。我相信这就是上帝对我们的期望:不求“完美”,也不求“从来不犯错误”,而是追求人生的“完整”。
如果我们有足够的勇气去爱,足够强大的力量去原谅别人,足够的宽容因别人的快乐而快乐,并有足够的智慧去认识到我们身边充满着爱,我们就会得到其它生命所得不到的一种满足感。

附录3

         人工智能(python)—— 目录汇总




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值