python: set 发表于 2017-05-24 | 分类于 python | 阅读次数 | 1234567891011121314151617181920212223242526272829303132>>> x = set("jihite")>>> y = set(['d', 'i', 'm', 'i', 't', 'e'])>>> x #把字符串转化为set,去重了set(['i', 'h', 'j', 'e', 't'])>>> yset(['i', 'e', 'm', 'd', 't'])>>> x & y #交set(['i', 'e', 't'])>>> x | y #并set(['e', 'd', 'i', 'h', 'j', 'm', 't'])>>> x - y #差set(['h', 'j'])>>> y - xset(['m', 'd'])>>> x ^ y #对称差:x和y的交集减去并集set(['d', 'h', 'j', 'm']) 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899>>> xset(['i', 'h', 'j', 'e', 't'])>>> s = set("hi")>>> sset(['i', 'h'])>>> len(x) #长度>>> 'i' in xTrue>>> s.issubset(x) #s是否为x的子集True>>> yset(['i', 'e', 'm', 'd', 't'])>>> x.union(y) #交set(['e', 'd', 'i', 'h', 'j', 'm', 't'])>>> x.intersection(y) #并set(['i', 'e', 't'])>>> x.difference(y) #差set(['h', 'j'])>>> x.symmetric_difference(y) #对称差set(['d', 'h', 'j', 'm'])>>> s.update(x) #更新s,加上x中的元素>>> sset(['e', 't', 'i', 'h', 'j'])>>> s.add(1) #增加元素>>> sset([1, 'e', 't', 'i', 'h', 'j'])>>> s.remove(1) #删除已有元素,如果没有会返回异常>>> sset(['e', 't', 'i', 'h', 'j'])>>> s.remove(2)Traceback (most recent call last): File "<pyshell#29>", line 1, in <module> s.remove(2)KeyError: 2>>> s.discard(2) #如果存在元素,就删除;没有不报异常>>> sset(['e', 't', 'i', 'h', 'j'])>>> s.clear() #清除set>>> sset([])>>> xset(['i', 'h', 'j', 'e', 't'])>>> x.pop() #随机删除一元素'i'>>> xset(['h', 'j', 'e', 't'])>>> x.pop()'h' Donate WeChat Pay Alipay