python 集合,,集合>>> a =


集合

>>> a = {1, ‘ff‘, 3} #创建集合

>>> type(a)

<class ‘set‘>

>>> a

{3, 1, ‘ff‘}

>>> b = {1, 2, 3, 3, 5, 5, 5, 7} #集合是无序的且集合中的元素不重复

>>> b

{1, 2, 3, 5, 7}

>>> b.add(66) #随机加入集合

>>> b

{1, 2, 3, 66, 5, 7}

>>> b.update([101, 99, 88]) #将迭代器中的元素追加到集合

>>> b

{1, 2, 3, 66, 5, 101, 7, 99, 88}

>>> b.remove(101) #删除集合里的某个元素

>>> b

{1, 2, 3, 66, 5, 7, 99, 88}

>>> b.discard(77) #删除集合内某个元素,如果集合内无此元素不做任何操作

>>> b

{1, 2, 3, 66, 5, 7, 99, 88}

>>> b.discard(66)

>>> b

{1, 2, 3, 5, 7, 99, 88}

>>> c = b.pop() #pop随机删除某个元素,并返回改元素

>>> b

{2, 3, 5, 7, 99, 88}

>>> c

1

>>> d = frozenset({1, 5, 77, 88, 100}) #创建不可变集合

>>> d

frozenset({1, 100, 5, 77, 88})

>>> d.add(7)

Traceback (most recent call last):

File "<pyshell#22>", line 1, in <module>

d.add(7)

AttributeError: ‘frozenset‘ object has no attribute ‘add‘


本文出自 “每天进步一点点” 博客,请务必保留此出处http://zuoshou.blog.51cto.com/2579903/1978731

python 集合

评论关闭