Python set(集合)注意事项和常用操作

2019-06-27  本文已影响0人  Cease息事

集合与常用操作

集合是工作中经常会使用到的一种数据类型; 使用起来也比较便捷, 下面是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

注 意

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

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

这里会传入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,那么里面嵌套的类型不能是这三种
为什么列表是不可哈希的,而 元组是可哈希的:

上一篇 下一篇

猜你喜欢

热点阅读