集合的定义,操作及运算 (Python),,集合的定义:集合和列
集合的定义,操作及运算 (Python),,集合的定义:集合和列
集合的定义:
集合和列表([ ]) 与 字典 ( { }) 不同,没有特别的特别的语法格式。可以使用set () 创建。
集合同字典一样是无序的。也是不具有重复性的。因此可以把列表变成集合进行去重。
集合具有特别的关系性能,交集,并集,差集等。
# hanbb come on!list1 = [1,4,5,7,3,6,7,9] # 列表s1 = set(list1) # remove repeat,such as 7 ; 自动去重 (列表转化为集合)s2 = set([1,6,0,66,22,8,4]) # another way express sets3 = set("hello") # 这是字符变成集合吗?print(s3) # {‘h‘, ‘o‘, ‘l‘, ‘e‘}print(s2) # {0, 2, 66, 4, 6, 8, 22}print(s1) # {1, 3, 4, 5, 6, 7, 9}
集合的基本操作:新增;移除;复制;求长度(没有修改?)
# basic operation# Add ones1.add(‘BB8‘)print(s1) # {1, 3, 4, 5, 6, 7, ‘BB8‘, 9}# add mores1.update( ["猪八戒","孙悟空"] ) # 注意[] # {1, ‘孙悟空‘, 3, 4, 5, 6, 7, ‘BB8‘, 9, ‘猪八戒‘}print(s1)# s1.update(2,4,6)s1.update([2,4,6]) # {1, 2, 3, 4, 5, 6, 7, 9, ‘猪八戒‘, ‘BB8‘, ‘孙悟空‘}print(s1)s1.update("BB7") # update"BB7" and add "BB8" 区别明显 # {1, 2, 3, 4, 5, 6, 7, 9, ‘7‘, ‘BB8‘, ‘孙悟空‘, ‘猪八戒‘, ‘B‘}print(s1)# Remove# s1.remove("1","2","3") # 不能移除多个 # remove() takes exactly one argument (3 given)# s1.remove(‘1‘) # 数据会出错,为啥呀 # s1.remove(‘1‘)s1.remove(‘B‘) # 字母不会,汉字也不会 # {1, 2, 3, 4, 5, 6, 7, 9, ‘猪八戒‘, ‘孙悟空‘, ‘BB8‘, ‘7‘}print(s1)# copys4 = s2.copy()print(s2)# lengthprint(len(s1)) # 12
集合的关系运算:交集,并集,差集(两个集合位置有影响),对称差集。
# relationshipprint(s1.intersection(s2)) # {1, 4, 6}print(s1.union(s2)) # {0, 1, 2, 3, 4, 5, 6, 7, 66, 9, 8, ‘7‘, ‘BB8‘, 22, ‘猪八戒‘, ‘孙悟空‘}print(s1.difference(s2)) # 在1中,不在2中 # {‘BB8‘, 2, 3, ‘7‘, 5, 7, 9, ‘孙悟空‘, ‘猪八戒‘}print(s2.difference(s1)) # 在2中,不在1中 # {0, 8, 66, 22}print(s1.symmetric_difference(s2)) # 对称差集(项在t或s中,但不会同时出现在二者中) # {0, 66, 2, ‘7‘, 3, 5, 8, 7, 9, ‘孙悟空‘, 22, ‘猪八戒‘, ‘BB8‘}
集合值的访问:
# 访问集合值print("1" in s1) # Falseprint("BB8" in s1) # True
print("1" not in s1) # Truefor i in s1: print(i) ‘‘‘1234567孙悟空9BB87猪八戒‘‘‘
集合还是比较容易理解和掌握的,还有操作符号的运算。
集合的定义,操作及运算 (Python)
相关内容
- Python中的self,,self代表类的实例
- windows7 上安装python3.8步骤,,今天给小白们写一个在
- Python 并发编程-进程,,Process类参数
- Python——课程数据统计分析,,介绍为训练营课程 《
- python 内置函数getattr,,在工作中遇到这个函数
- python pandas.merge() 函数 解析,,merge()函数主
- Python str类的 find() 方法,,(str).find
- python求均值、方差、标准差,,import num
- Python编程练习(一),,学习中,都是从书上找
- 如何将 Debian Linux 中的默认的 Python 版本切换为替代版本
评论关闭