1.在尾部添加一项
add(...)
This has no effect if the element is already present
>>> a = set([1,2,3,4,5])
>>> a.add(‘shaw‘)
>>> a
set([1, 2, 3, 4, 5, ‘shaw‘])
2.清空集合中所有元素
clear(...)
Remove all elements from this set
>>>a = set([1, 2, 3, 4, 5, ‘shaw‘])
>>>a.clear()
>>>a
set([])
3.返回一个新集合,但是新集合中的元素,a中有,b中没有
difference(...)
>>> a = set([1, 2, 3, 4, 5,‘shaw‘])
>>> b = set([2,3,5,‘sam‘])
>>> a.difference(b)
set([1, 4, ‘shaw‘])
4.从set a中删除,集合a和集合b同时拥有的元素
difference_update(...)
>>> a = set([1, 2, 3, 4, 5,‘shaw‘])
>>> b = set([2,3,5,‘sam‘])
>>> a.difference_update(b)
>>> a
set([1, 4, ‘shaw‘])
>>> b
set([2, 3, 5, ‘sam‘])
5.删除set中指定元素(即使这个元素不存在与这个集合中,不会报错)
discard(...)
Remove an element from a set if it is amember.f the element is not a member, do nothing.
>>> a = set([1, 2, 3, 4, 5,‘shaw‘])
>>> a.discard(‘5‘)
>>> a
set([1, 2, 3, 4, 5, ‘shaw‘])
>>> a.discard(‘sam‘)
>>> a
set([1, 2, 3, 4, 5, ‘shaw‘])
6.返回一个新集合,新集合元素由set a和set b的交集组成
intersection(...)
Return the intersection of two or more setsas a new set.
>>> a = set([1, 2, 3, 4, 5,‘shaw‘])
>>> b = set([2,3,5,‘sam‘])
>>> a.intersection(b) 等同于 a & b
set([2, 3, 5])
7.从set a中删除,a和b交集之外的元素
intersection_update(...)
>>> a = set([1, 2, 3, 4, 5,‘shaw‘])
>>> b = set([2,3,5,‘sam‘])
>>> a.intersection_update(b)
>>> a
set([2, 3, 5])
8.判断两个集合是否有交集,如果有,则返回True,否则返回False
isdisjoint(...)
>>> a = set([1, 2, 3, 4, 5,‘shaw‘])
>>> b = set([2,3,5,‘sam‘])
>>> a.isdisjoint(b)
False
>>> c = set([9,‘alices‘])
>>> a.isdisjoint(c)
True
9.测试一个集合中的元素是否都在另一个元素中(即测试集合b是否是集合a的子集)
issubset(...)
Report whether another set contains this set
注:
issuperset(...)
Report whether this set contains another set
>>> a = set([1, 2, 3, 4, 5,‘shaw‘])
>>> b = set([2,3,5,‘sam‘])
>>> c = set([5,‘shaw‘])
>>> b.issubset(a)
False
>>> c.issubset(a) 等同于 c <= a
True
10.删除一个元素(默认删除第一项),如果要删除的元素不存在,则报keyerror
pop(...)
>>>a = set([1, 2, 3, 4, 5, ‘shaw‘])
>>>a.pop()
1
>>>a
set([2,3, 4, 5, ‘shaw‘])
11. 删除指定元素,如果要删除的元素不存在,则报keyerror
remove(...)
>>> a = set([1, 2, 3, 4, 5,‘shaw‘])
>>> a.remove(1)
>>> a
set([2, 3, 4, 5, ‘shaw‘])
>>> a.remove(‘shaw‘)
>>> a
set([2, 3, 4, 5])
12.对称差集(此元素在a中有且b中没有,和b中有且a中没有的元素)
symmetric_difference(...)
>>> a = set(‘abcdef‘)
>>> b = set(‘abcklyt‘)
>>> a.symmetric_difference(b)
set([‘e‘, ‘t‘, ‘f‘, ‘y‘, ‘k‘, ‘l‘, ‘d‘])
>>> a ^ b
set([‘e‘, ‘t‘, ‘f‘, ‘y‘, ‘k‘, ‘l‘, ‘d‘])
13.取并集(返回一个新的 set 包含 s 和t 中的每一个元素)
union(...)
>>> a = set(‘acdf‘)
>>> b = set(‘adkh‘)
>>> a.union(b)
set([‘a‘, ‘c‘, ‘d‘, ‘f‘, ‘h‘, ‘k‘])
>>> a | b
set([‘a‘, ‘c‘, ‘d‘, ‘f‘, ‘h‘, ‘k‘])
14.向集合a中添加元素(添加另一个集合时,会去除重复的元素)
update(...)
>>> a = set(‘acdf‘)
>>> b = set(‘adkh‘)
>>> a.update(b)
>>> a
set([‘a‘, ‘c‘, ‘d‘, ‘f‘, ‘h‘, ‘k‘])
>>> a = set(‘acdf‘)
>>> b = set(‘adkh‘)
>>> a |= b
>>> a
set([‘a‘, ‘c‘, ‘d‘, ‘f‘, ‘h‘, ‘k‘])
>>> a= set(‘shaw‘)
>>> a.update(‘bnga‘)
>>> a
set([‘a‘, ‘b‘, ‘g‘, ‘h‘, ‘n‘, ‘s‘, ‘w‘])
本文出自 “Shaw Blog” 博客,请务必保留此出处http://opsedu.blog.51cto.com/9265055/1762866
原文地址:http://opsedu.blog.51cto.com/9265055/1762866