【Python】10、python内置数据结构之集合
## set.remove()In : s
Out: {'a', 'b', 'j', 'x'}
In : s.remove("a")
In : s
Out: {'b', 'j', 'x'}
In : s.remove("S")
-----------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-151-332efdd48daa> in <module>()
----> 1 s.remove("S")
KeyError: 'S'
## set.pop()
In : s = {1, 2, 3, 4}
In : s.pop()
Out: 1
In : s
Out: {2, 3, 4}
In : s.pop(5)
-----------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-156-23a1c03efc29> in <module>()
----> 1 s.pop(5)
TypeError: pop() takes no arguments (1 given)
In : s.pop()
Out: 2
In : s.pop()
Out: 3
In : s.pop()
Out: 4
In : s.pop()
-----------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-160-e76f41daca5e> in <module>()
----> 1 s.pop()
KeyError: 'pop from an empty set'
## set.discard()
In : help(set.discard)
Help on method_descriptor:
discard(...)
Remove an element from a set if it is a member.
If the element is not a member, do nothing.
In : s = {1, 2, 3}
In : s.discard(2)
In : s.discard(1, 3)
-----------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-168-8702b734cbc4> in <module>()
----> 1 s.discard(1, 3)
TypeError: discard() takes exactly one argument (2 given)
In : s.discard(2) # 元素不存在时,不会报错
In : s
Out: {1, 3}
In : s.clear()
In : s
Out: set()
In : del(s)
In : s
-----------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-48-f4d5d0c0671b> in <module>()
----> 1 s
NameError: name 's' is not defined
页:
[1]