赞
踩
无序不重复序列,可使用{}或set()函数创建集合,空集合只能使用set()
集合中元素只能是字符串、数字、元组
{value1, value2,...} 或 set(value)
>>> set1 = {'apple', 'orange', 'apple', 'banana'}
>>> set1
{'orange', 'apple', 'banana'}
>>> set1 = set({'apple', 'orange', 'apple', 'banana'})
>>> set1
{'orange', 'apple', 'banana'}
>>> type(set())
<class 'set'>
>>> type({})
<class 'dict'>
set1.intersection(set2)
>>> set1 = {'apple', 'orange'}
>>> set2 = {'orange', 'banana'}
>>> set1.intersection(set2)
{'orange'}
set1.union(set2)
>>> set1 = {'apple', 'orange'}
>>> set2 = {'orange', 'banana'}
>>> set1.union(set2)
{'orange', 'apple', 'banana'}
set1.difference(set2)
set1中不同于set2中的元素
>>> set1 = {'apple', 'orange'}
>>> set2 = {'orange', 'banana'}
>>> set1.difference(set2)
{'apple'}
set1.symmetric_difference(set2)
并集去除重复
>>> set1 = {'apple', 'orange'}
>>> set2 = {'orange', 'banana'}
>>> set1.symmetric_difference(set2)
{'apple', 'banana'}
set.add(obj)
obj为不可变数据类型
>>> set1 = {'apple', 'orange'} >>> set1.add(1) >>> set1.add('banbana') >>> set1.add((1, 3, 4)) >>> set1 {1, 'banbana', 'apple', (1, 3, 4), 'orange'} >>> set1.add([1, 3]) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'list' >>> set1.add({'k':'v'}) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'dict' >>> set1.add({1, 3}) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'set'
set.update(obj)
obj为可迭代对象,字符串是单个字符作为元素添加,其他数据结构单个元素添加
>>> set1 = {'apple', 'orange'}
>>> set1.update('chinese')
>>> set1
{'apple', 'h', 'n', 'c', 's', 'orange', 'i', 'e'}
>>> set1.update(["banana", 'grape'])
>>> set1
{'apple', 'banana', 'h', 'n', 'c', 's', 'grape', 'orange', 'i', 'e'}
>>> set1.update(["joker", '95'])
>>> set1
{'apple', 'banana', 'h', 'n', 'c', '95', 's', 'grape', 'orange', 'i', 'e', 'joker'}
set.pop()
>>> set1 = {'apple', 'orange', 'grape', 'banbana'}
>>> set1.pop()
'grape'
>>> set1
{'orange', 'apple', 'banbana'}
>>> set1.pop()
'orange'
>>> set1
{'apple', 'banbana'}
set.remove(value)
不存在报错
>>> set1 = {'apple', 'orange', 'grape', 'banbana'}
>>> set1.remove('apple')
>>> set1
{'grape', 'orange', 'banbana'}
>>> set1.remove('apple')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'apple'
set.discard(value)
不存在不作操作
>>> set1 = {'apple', 'orange', 'grape', 'banbana'}
>>> set1.discard('apple')
>>> set1
{'grape', 'orange', 'banbana'}
>>> set1.discard('apple')
>>>
set.clear()
>>> set1 = {'apple', 'orange', 'grape', 'banbana'}
>>> set1.clear()
>>> set1
set()
set1.isdisjoint(set2)
不相交返回True,相交返回False
>>> set1 = {1, 3, 5}
>>> set2 = {3, 5, 7}
>>> set1.isdisjoint(set2)
False
set1.issubset(set2)
>>> set1 = {3, 5}
>>> set2 = {1, 3, 5}
>>> set1.issubset(set2)
True
set1.issuperset(set2)
>>> set1 = {1, 3, 5}
>>> set2 = {3, 5}
>>> set1.issuperset(set2)
True
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。