百度 Google Bing
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

python3集合与常用操作

Posted on 2019-06-27 19:23  都说是捡便宜了  阅读(257)  评论(0编辑  收藏  举报

集合与常用操作

集合是工作中经常会使用到的一种数据类型; 使用起来也比较便捷, 下面是python中集合的常见操作;

关系测试:

操作 方法 运算符
交集 intersection() &
并集 union() |
子集 issubset() <
父集 issuperset() >
差集 difference() -
对称差集 symmetric_difference() ^
#Return True if two set have a null intersection
set_1 = {1,2,3,4}
set_2 = {2,3}
set_2.isdisjoint(set_1) # False

集合操作

example: set_1 = {2, 6, 8}

添加:

set_1.add(10) #Add an element to a set. This has no effect if the element is already present.
set_1.update([1, 3, 5]) #Update a set with the union of itself and others.

删除

set_1.pop() #Remove and return an arbitary set element. Raises KeyError if the set is empty.
set_1.remove(2) #Remove an element from a set; it must be a member. if not, raise KetError
set_1.discard(888) #Remove an element from a set if it is a member. if not, do nothing

注 意

update()方法传入嵌套数据类型会怎么样?

这里假如set_1.update([7,8,(9,10)]), 结果会报错吗?

这里会传入set_1,得到 {7,8,(9,10)}

那么如果传入的是 [7,8,[9,10]]又会怎么样呢?

当然了,传入这样的嵌套格式是会报错(TypeError: unhashable type: 'list')的, 原因如下:

类型错误,不可拆卸类型,也叫不可哈希。出现这种异常是因为在使用set()过程中,set()传递进来的是不可哈希的元素,而列表嵌套内部由于不分解,要被当做集合内的元素,必须是可哈希的,我们知道,在集合的定义中,set中的元素是不重复的,无序的,里面的元素必须是可哈希的,即不可变的(int,str,tuple,bool)
可哈希的元素有:int、float、str、tuple
不可哈希的元素有:list、set、dict,那么里面嵌套的类型不能是这三种
为什么列表是不可哈希的,而 元组是可哈希的:

  • 因为 list 是可变的,可以在任意改变其内的元素值。
  • 元素可不可哈希,决定是否使用 hash值 进行索引
  • 列表不使用 hash 进行元素的索引,自然它对存储的元素没有可哈希的要求;而集合使用 hash 值进行索引。