06集合

集合
set
唯一性
无序性,不可索引
1.集合的创建
①{}括起一堆元素
②使用工厂函数set()
变量可以是元组 列表 字符串 集合


去除掉列表中的重复元素
>>> num1 = {3,5,4,1,2,5,8,0,1,2,3}
>>> temp = []
>>> for each in num1:
	if each not in temp:
		temp.append(each)


>>> num1 = {3,5,4,1,2,5,8,0,1,2,3}
>>> num1 = list(set(num1))
>>> num1
[0, 1, 2, 3, 4, 5, 8]
2.访问集合中的值
①可以使用for把集合中的数据一个个读取
②通过in 和 not in 判断一个元素是否在集合中已经存在

3.对集合的操作
①add()
>>> num2 = {1,2,33,0}
>>> num2.add(5)
>>> num2
{0, 1, 2, 33, 5}

②remove()
>>> num3 = {3,8,0,1,2}
>>> num3.remove(8)
>>> num3
{0, 1, 2, 3}

4.不可变集合
frozenset()
>>> a = frozenset([2,5,3,1,0])
>>> a
frozenset({0, 1, 2, 3, 5})
>>> a.add(4)
Traceback (most recent call last):
  File "<pyshell#31>", line 1, in <module>
    a.add(4)
AttributeError: 'frozenset' object has no attribute 'add'

5.集合的数学运算   &|^   交并补
>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> print(basket)                      # show that duplicates have been removed
{'orange', 'banana', 'pear', 'apple'}
>>> 'orange' in basket                 # fast membership testing
True
>>> 'crabgrass' in basket
False

>>> # Demonstrate set operations on unique letters from two words
...
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a                                  # unique letters in a
{'a', 'r', 'b', 'c', 'd'}
>>> a - b                              # letters in a but not in b
{'r', 'd', 'b'}
>>> a | b                              # letters in a or b or both
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b                              # letters in both a and b
{'a', 'c'}
>>> a ^ b                              # letters in a or b but not both
{'r', 'd', 'b', 'm', 'z', 'l'}



Similarly to list comprehensions, set comprehensions are also supported:

>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
{'r', 'd'}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值