首頁  >  文章  >  後端開發  >  Python內建函數-set&frozenset

Python內建函數-set&frozenset

黄舟
黄舟原創
2017-01-19 16:35:071575瀏覽


Python內建函數-set&frozenset


set
set()
set对象实例化
>>> set('add')
set(['a', 'd'])
>>> set('python').add('hello')
>>> print set('python').add('hello')
None
>>> a = set('python')
>>> a
set(['h', 'o', 'n', 'p', 't', 'y'])
>>> a.add('hello')
>>> a
set(['h', 'o', 'n', 'p', 't', 'y', 'hello'])
>>> a.update('python')
>>> a
set(['h', 'o', 'n', 'p', 't', 'y', 'hello'])
>>> a.update('hello')
>>> a
set(['e', 'h', 'l', 'o', 'n', 'p', 't', 'y', 'hello'])
>>> a.remove('hello')
>>> a
set(['e', 'h', 'l', 'o', 'n', 'p', 't', 'y'])
>>> b = set('hello')
>>> b
set(['h', 'e', 'l', 'o'])
>>> a - b
set(['y', 'p', 't', 'n'])
>>> a & b
set(['h', 'e', 'l', 'o'])
>>> a | b
set(['e', 'h', 'l', 'o', 'n', 'p', 't', 'y'])
>>> a != b
True
>>> a == b
False
>>> b in a
False
>>> a in b
False
>>> c = set('hell')
>>> c in b
False
>>> b
set(['h', 'e', 'l', 'o'])
>>> c
set(['h', 'e', 'l'])
>>> 'h' in c
True
>>> 'p' in c
False

frozenset

set
frozenset([iterable])
产生一个不可变的set
>>> a = frozenset(range(10))
>>> a
frozenset([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> a.remove(0)
Traceback (most recent call last):
  File "<pyshell#189>", line 1, in <module>
    a.remove(0)
AttributeError: &#39;frozenset&#39; object has no attribute &#39;remove&#39;
>>> b = set(range(10))
>>> b
set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> b.remove(1)
>>> b
set([0, 2, 3, 4, 5, 6, 7, 8, 9])

)!


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn