Home  >  Article  >  Backend Development  >  Python built-in function——set&frozenset

Python built-in function——set&frozenset

黄舟
黄舟Original
2017-01-19 16:35:071619browse


Python built-in function - 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

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])
The above is the content of Python’s built-in function-set&frozenset. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn