collection of datasets

feature

1. Deterministic (elements must be hashable)
2. Mutuality (de-duplication)
3. Disordered (elements in the set have no order, precedence)

>>> s = {1,1,1,2,2,3,4,5,6,7}    # 创建
>>> s
{1, 2, 3, 4, 5, 6, 7}
>>> s.add(2)                    # 添加,重复添加也添加不上
>>> s.add(22)
>>> s
{1, 2, 3, 4, 5, 6, 7, 22}
>>> s.update([11,33,44])        # 添加批量元素
>>> s
{1, 2, 3, 4, 5, 6, 7, 33, 11, 44, 22}
>>> s.discard(7)                # 删除指定元素
>>> s.pop()                        # 删除随机元素,pop()没有参数
1
>>> s.pop(2)
Traceback (most recent call last):
  File "<pyshell#14>", line 1, in <module>
    s.pop(2)
TypeError: pop() takes no arguments (1 given)
>>> s.clear()                    # 清空集合
>>> s
set()
>>> s.add(1)
>>> s.copy()                    # 复制
{1}
>>> s.update([11,33,44])
>>> s
{1, 11, 44, 33}
>>> s.copy()
{1, 11, 44, 33}
>>> s.add([12,13,14])            # 不能添加非 hash 元素
Traceback (most recent call last):
  File "<pyshell#22>", line 1, in <module>
    s.add([12,13,14])
TypeError: unhashable type: 'list'
>>>

Collection relationship test

>>> stu1 = {'python','linux','html','mysql'}
>>> stu2 = {'linux','python','go','css','javascript'}
>>> stu1.intersection(stu2)            # 交集,两个集合都有的
{'python', 'linux'}
>>> stu1 & stu2
{'python', 'linux'}
>>> stu1.difference(stu2)            # 差集,除了都有的,比后者不同的部分就是差集
{'mysql', 'html'}
>>> stu1 - stu2                        # 相同的,负的都去掉,剩下的是差集
{'mysql', 'html'}
>>> stu2 - stu1                        # 前者不同于后者的部分
{'javascript', 'go', 'css'}


>>> stu1.union(stu2)                # 并集,合并两者所有的
{'linux', 'javascript', 'html', 'mysql', 'python', 'go', 'css'}
>>> stu2 | stu1
{'linux', 'javascript', 'python', 'go', 'css', 'html', 'mysql'}


>>> stu1.symmetric_difference(stu2)            # 对称差集,并集去掉交集
{'javascript', 'go', 'css', 'html', 'mysql'}
>>> stu2 ^ stu1
{'javascript', 'html', 'mysql', 'go', 'css'}


>>> stu1.difference_update(stu2)                # 将差集,赋给 stu1     同理交集也可以
>>> stu1
{'html', 'mysql'}





Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324772059&siteId=291194637