set is an unordered collection of elements,is a map in which keys do not have associated values.
python have builtins frozenset and set.frozenset is an immutable form. these are implemented using hash table.
-
from collections import MutableSet #set
-
from collections import Set #immutable set
基本操作:
-
some_set={7,2,3,5}
-
some_set.add(6) #add the item
-
some_set.update({10,9}) #add new set to this set
-
some_set.remove(6) #remove if the item exist, or raise an KeyError Exception.
-
some_set.discard(6) #discard an item and no exception if it does not exist.
-
some_set.pop() #return an arbitrary item, raise KeyError if set is empty.
-
some_set.clear() #清空一个集合
-
sorted(some_set)
-
max(some_set)
-
min(some_set)
-
sum(some_set)
-
words=set('How I wish'.split())
-
more=set('I would recollect pi'.split())
-
words|more #words.union(more) 并集
-
words&more #words.intersection(more) 交集
-
words|=more #words.update(more) 把第二个集合中不在第一个集合中的数据加入到第一个集合
-
words-more #words.difference(more) 第一个集合减去两个集合的交集
-
words^more #words.symmetric_difference(more) 剪去两个集合的交集,并把第二个集合中特有的元素加入第一个集合
-
{1,2,3}.issubset({1,2,3,4,5,6}) #第一个集合是第二个集合的子集
-
{1,2,3,4,5}.issubset({1,2,3}) #False
-
{1,2,3}.issuperset({1,2,3,4,5,6}) #False
-
{1,2,3,4,5,6}.issuperset({1,2,3}) #第一个集合是第二个集合的超集
-
not({1,2,3}-{1,2,3,4,5}) #True,空集合为False
-
not({1,2,3,4,5}-{1,2,3}) #False
-
-
'I' in words #True
-
{'I'} < words #True
-
{'How','I','wish'} <= words #True
-
S|T: | 是用__or__实现的
-
S|=T:是__ior__ 实现
-
表示空集合用 set() ,最好不用{}
阅读(2010) | 评论(1) | 转发(0) |