這篇文章將為大家詳細講解有關set在python里怎么用,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
set在python里是什么意思?
set是一組數,無序,內容又不能重復,通過調用set()方法創建:
>>> s = set(['A', 'B', 'C'])
對于訪問一個set的意義就僅僅在于查看某個元素是否在這個集合里面,注意大小寫敏感:
>>> print 'A' in s True >>> print 'D' in s False
也通過for來遍歷:
s = set([('Adam', 95), ('Lisa', 85), ('Bart', 59)]) for x in s: print x[0],':',x[1] >>> Lisa : 85 Adam : 95 Bart : 59
通過add和remove來添加、刪除元素(保持不重復),添加元素時,用set的add()方法
>>> s = set([1, 2, 3]) >>> s.add(4) >>> print s set([1, 2, 3, 4])
如果添加的元素已經存在于set中,add()不會報錯,但是不會加進去了:
>>> s = set([1, 2, 3]) >>> s.add(3) >>> print s set([1, 2, 3])
刪除set中的元素時,用set的remove()方法:
>>> s = set([1, 2, 3, 4]) >>> s.remove(4) >>> print s set([1, 2, 3])
如果刪除的元素不存在set中,remove()會報錯:
>>> s = set([1, 2, 3]) >>> s.remove(4) Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 4
所以如果我們要判斷一個元素是否在一些不同的條件內符合,用set是最好的選擇,下面例子:
months = set(['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec',]) x1 = 'Feb' x2 = 'Sun' if x1 in months: print 'x1: ok' else: print 'x1: error' if x2 in months: print 'x2: ok' else: print 'x2: error' >>> x1: ok x2: error
另外,set的計算效率比list高.
關于set在python里怎么用就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。