>>> seq = [1,2,3,1,2,3,'a','hello','a','world']
>>> seq_set = set(seq)
>>> seq_set
set(['a', 1, 2, 3, 'world', 'hello']) #去除了重复对象
>>> string = "hello world"
>>> string_set = set(string)
>>> string_set
set([' ', 'e', 'd', 'h', 'l', 'o', 'r', 'w']) #sting也是Python中的一种序列
#set是一种集合,当然可以使用 in/not in, len
>>> 'h' in string_set
True
>>> 'a' in string_set
False
>>> len(string_set)
8
#set的增删操作
# s.add(x)
# 向 set “s”中增加元素 x
# s.remove(x)
# 从 set “s”中删除元素 x, 如果不存在则引发 KeyError
# s.discard(x)
# 如果在 set “s”中存在元素 x, 则删除
# s.pop()
# 删除并且返回 set “s”中的一个不确定的元素, 如果为空则引发 KeyError
# s.clear()
# 删除 set “s”中的所有元素
>>> set1 = set([1])
>>> set1
set([1])
>>> set1.add(2)
>>> set1
set([1, 2])
>>> set1.remove(3)
Traceback (most recent call last):
File "<pyshell#47>", line 1, in <module>
set1.remove(3)
KeyError: 3
>>> set1.remove(2)
>>> set1
set([1])
>>> set1.discard(2)
>>> set1
set([1])
>>> set1.discard(1)
>>> set1
set([])
>>> set1.add([1,2,3,4])
Traceback (most recent call last):
File "<pyshell#54>", line 1, in <module>
set1.add([1,2,3,4])
TypeError: unhashable type: 'list'
>>> set1 = set([1,2,3,4,5])
>>> set1.pop()
1
>>> set1
set([2, 3, 4, 5])
>>> set1.clear()
>>> set1
set([])
>>>
转自http://blog.csdn.net/sicofield/article/details/40083653