Python集
集合用于将多个项目存储在单个变量中。
Set 是 Python 中用于存储数据集合的 4 种内置数据类型之一,另外 3 种是List、 Tuple和Dictionary,它们都具有不同的质量和用途。
集合是无序、不可更改*和未索引的集合。
#创建一个集合: thisset = {"apple", "banana", "cherry"}
print(len(thisset))
设置项 - 数据类型
集合项可以是任何数据类型:
set1 = {"apple", "banana", "cherry"}
set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}
一个集合可以包含不同的数据类型
set() 构造函数
也可以使用set() 构造函数来创建一个集合。
thisset = set(("apple", "banana", "cherry")) # note the double round-brackets
访问项目
您不能通过引用索引或键来访问集合中的项目。
但是您可以使用循环遍历集合项,或者使用关键字for 询问集合中是否存在指定值 。
for x in thisset: print(x) #检查集合中是否存在“香蕉”: print("banana" in thisset)
添加项目
要将一个项目添加到集合中,请使用该add() 方法。
thisset.add("orange")
添加集
要将另一个集合中的项目添加到当前集合中,请使用该update() 方法。
thisset = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}
thisset.update(tropical)
添加任何可迭代对象
方法中的对象update()不必是集合,它可以是任何可迭代的对象(元组、列表、字典等)。
thisset = {"apple", "banana", "cherry"}
mylist = ["kiwi", "orange"]
thisset.update(mylist)
除去项目
要删除集合中的项目,请使用remove()或discard()方法。
thisset = {"apple", "banana", "cherry"}
thisset.remove("banana")
#注意:如果要删除的项目不存在,remove()将引发错误。
thisset = {"apple", "banana", "cherry"}
thisset.discard("banana")
#注意:如果要删除的项目不存在,discard()则 不会引发错误。
您也可以使用该pop()方法删除一个项目,但此方法将删除最后一个项目。请记住,集合是无序的,因此您将不知道要删除的项目。
该pop()方法的返回值是被移除的项目。
thisset = {"apple", "banana", "cherry"}
x = thisset.pop()
print(x)
print(thisset)
该clear() 方法清空集合:
thisset = {"apple", "banana", "cherry"}
thisset.clear()
该del关键字将完全删除该集合:
thisset = {"apple", "banana", "cherry"}
del thisset
循环项目
您可以使用循环遍历设置的项目for :
for x in thisset:
print(x)
连接集
在 Python 中有几种方法可以连接两个或多个集合。
您可以使用union()返回包含两个集合中所有项目的新集合的方法,或将一个集合中的所有项目update()插入另一个集合的方法:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set1.update(set2)
只保留重复项
该intersection_update()方法将仅保留两个集合中都存在的项目。
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.intersection_update(y)
该intersection()方法将返回一个新集合,该集合仅包含两个集合中都存在的项目。
z = x.intersection(y)
保留所有,但不保留重复项
该symmetric_difference_update()方法将仅保留两个集合中都不存在的元素。
x.symmetric_difference_update(y)
浙公网安备 33010602011771号