Python集
组
集合是无序且无索引的集合。在Python中,集合用大括号括起来。
注意:集合是无序的,因此您不能确定项目将以什么顺序出现。
存取项目
您不能通过引用索引或键来访问集合中的项目。
但是,您可以使用循环来遍历设置项for
,也可以使用in
关键字询问设置中是否存在指定值
。
变更项目
创建集后,您将无法更改其项目,但可以添加新项目。
新增项目
要将一个项目添加到集合中,请使用add()
方法。
要向一个集合中添加多个项目,请使用update()
方法。
例
使用以下add()
方法将项目添加到集合中:
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
自己尝试»
例
使用以下update()
方法将多个项目添加到集合中:
thisset = {"apple", "banana", "cherry"}
thisset.update(["orange",
"mango", "grapes"])
print(thisset)
自己尝试»
获取集合的长度
要确定一组有多少项,请使用len()
方法。
除去项目
要删除集合中的项目,请使用remove()
或discard()
方法。
例
使用以下remove()
方法删除“香蕉” :
thisset = {"apple", "banana", "cherry"}
thisset.remove("banana")
print(thisset)
自己尝试»
注意:如果要删除的项目不存在,remove()
将引发错误。
例
使用以下discard()
方法删除“香蕉” :
thisset = {"apple", "banana", "cherry"}
thisset.discard("banana")
print(thisset)
自己尝试»
注意:如果要删除的项目不存在,discard()
则
不会引发错误。
您也可以使用pop()
,方法删除一个项目,但是此方法将删除最后一个项目。请记住,集合是无序的,因此您将不知道要删除的项目。
该pop()
方法的返回值是删除的项目。
例
使用以下pop()
方法删除最后一项:
thisset = {"apple", "banana", "cherry"}
x =
thisset.pop()
print(x)
print(thisset)
自己尝试»
注意:集合是无序的,因此使用该pop()
方法时,您将不知道要删除的项。
结合两组
有几种方法可以在Python中连接两个或多个集合。
您可以使用union()
返回包含两个集合中所有项目的新集合的方法,也可以使用将一个集合中的所有项目update()
插入另一个集合的方法:
例
该union()
方法返回一个新集合,其中包含两个集合中的所有项目:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)
自己尝试»
例
该update()
方法将set2中的项目插入set1中:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set1.update(set2)
print(set1)
自己尝试»
注意:无论union()
和update()
将排除任何重复的项目。
还有其他方法将两个集合连接起来,并且仅保留重复项,或者永远不保留重复项,请检查此页面底部的set方法的完整列表。
set()构造函数
也可以使用set() 构造函数进行设置。
例
使用set()构造函数进行设置:
thisset = set(("apple", "banana", "cherry")) # note the double round-brackets
print(thisset)
自己尝试»
设定方法
Python有一组内置方法,可在集合上使用。
Method | Description |
---|---|
add() | Adds an element to the set |
clear() | Removes all the elements from the set |
copy() | Returns a copy of the set |
difference() | Returns a set containing the difference between two or more sets |
difference_update() | Removes the items in this set that are also included in another, specified set |
discard() | Remove the specified item |
intersection() | Returns a set, that is the intersection of two other sets |
intersection_update() | Removes the items in this set that are not present in other, specified set(s) |
isdisjoint() | Returns whether two sets have a intersection or not |
issubset() | Returns whether another set contains this set or not |
issuperset() | Returns whether this set contains another set or not |
pop() | Removes an element from the set |
remove() | Removes the specified element |
symmetric_difference() | Returns a set with the symmetric differences of two sets |
symmetric_difference_update() | inserts the symmetric differences from this set and another |
union() | Return a set containing the union of sets |
update() | Update the set with the union of this set and others |