当前位置:Gxlcms > Python > Python内置函数——set&frozenset

Python内置函数——set&frozenset

时间:2021-07-01 10:21:17 帮助过:22人阅读

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

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: 'frozenset' object has no attribute 'remove'
>>> 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])

以上就是Python内置函数——set&frozenset的内容,更多相关内容请关注PHP中文网(www.gxlcms.com)!

人气教程排行