python-11 数据结构 - 集合

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/L1558198727/article/details/83014474

分类

可变集合:
创建
	字面量创建
		{值}
		 值: 整形 字符串 元组
		 只能是固定类型,不可以是列表,可以是元组
		 >>> {1,2,3,}
		{1, 2, 3}
		>>> {1,"s"}
		{1, 's'}
		>>> {1,1.2,True}
		{1, 1.2}
		>>> {11,True}
		{True, 11}
	通过对象创建
	set()
	>>> set2 = set("hello")
	>>> set
	<class 'set'>
	>>> set2
	{'l', 'e', 'h', 'o'}
	
	>>> set3 = set([1,2,3,4])
	>>> set3
	{1, 2, 3, 4}

	frozenset()
	>>> set3 = frozenset("hello")
	>>> set3
	frozenset({'l', 'e', 'h', 'o'})
	推导式
	>>> {x*x for x in range(5)}
	{0, 1, 4, 9, 16}
	
不可变集合:

交集

>>> {1,False}
{False, 1}

>>> {1,1.0}
{1}

>>> {1,True}
{1}

集合的操作

遍历访问:
>>> set1 = {1,2,3,6,7,8,5,4}
>>> for i in set1:
	print(i,end="")
	
12345678

成员判断 
in 
not in 


>>> set1={1,2,3}
>>> set2 = {2,3,4,5,6}
并集
>>> set1| set2
{1, 2, 3, 4, 5, 6}
交集
>>> set1 & set2
{2, 3}
差集
>>> set1 - set2
{1}
对差
>>> set1 ^ set2
{1, 4, 5, 6}

>>> set1==set2
False
>>> set1>set2
False
>>> set1<set2
False
>>> len(set1)
3

集合的合并
>>> set1
{1, 2, 3}
>>> set2
{2, 3, 4, 5, 6}
>>> set1.update(set2)
>>> set1
{1, 2, 3, 4, 5, 6}


copy():
>>> set1
{1, 2, 3, 4, 5}
>>> set2 = set1.copy()
>>> set2
{1, 2, 3, 4, 5}

不支持索引

猜你喜欢

转载自blog.csdn.net/L1558198727/article/details/83014474