Python集合方法
Python中的Set是无序且可变的唯一元素的集合。 Python提供了各种与 Set 一起使用的函数。在本文中,我们将看到Python提供的用于处理 Set 的所有函数的列表。
添加和删除元素
我们可以在以下函数的帮助下从集合中添加和删除元素 -
- add():将给定元素添加到集合中
- clear():从集合中删除所有元素
- 丢弃():从集合中删除元素
- pop():从集合中返回并移除一个随机元素
- remove():从集合中移除元素
示例:从集合中添加和删除元素。
Python3
# set of letters
s = {'g', 'e', 'k', 's'}
# adding 's'
s.add('f')
print('Set after updating:', s)
# Discarding element from the set
s.discard('g')
print('\nSet after updating:', s)
# Removing element from the set
s.remove('e')
print('\nSet after updating:', s)
# Popping elements from the set
print('\nPopped elememt', s.pop())
print('Set after updating:', s)
s.clear()
print('\nSet after updating:', s)
输出
Set after updating: {'k', 's', 'g', 'e', 'f'}
Set after updating: {'k', 's', 'e', 'f'}
Set after updating: {'k', 's', 'f'}
Popped elememt k
Set after updating: {'s', 'f'}
Set after updating: set()
Python Set 方法表
Functions Name | Description |
---|---|
add() | Adds a given element to a set |
clear() | Removes all elements from the set |
copy() | Returns a shallow copy of the set |
difference() | Returns a set that is the difference between two sets |
difference_update() | Updates the existing caller set with the difference between two sets |
discard() | Removes the element from the set |
frozenset() | Return an immutable frozenset object |
intersection() | Returns a set that has the intersection of all sets |
intersection_update() | Updates the existing caller set with the intersection of sets |
isdisjoint() | Checks whether the sets are disjoint or not |
issubset() | Returns True if all elements of a set A are present in another set B |
issuperset() | Returns True if all elements of a set A occupies set B |
pop() | Returns and removes a random element from the set |
remove() | Removes the element from the set |
symmetric_difference() | Returns a set which is the symmetric difference between the two sets |
symmetric_difference_update() | Updates the existing caller set with the symmetric difference of sets |
union() | Returns a set that has the union of all sets |
update() | Adds elements to the set |
注意:有关Python集的更多信息,请参阅Python集教程。