python set

>>> 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
發佈了20 篇原創文章 · 獲贊 4 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章