Python教程-Python 集合(Set)
Python 集合是一种无序项目的集合。集合中的每个元素必须是唯一的、不可变的,并且集合会移除重复的元素。集合是可变的,这意味着我们可以在创建后修改它。
与Python中的其他集合不同,集合的元素没有附加索引,即我们不能通过索引直接访问集合的任何元素。然而,我们可以一起打印它们,或者可以通过循环遍历集合获取元素的列表。
创建集合
集合可以通过用大括号 {}
括起逗号分隔的不可变项来创建。Python 还提供了 set()
方法,该方法可以用于通过传递序列来创建集合。
使用花括号创建集合
Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}
print(Days)
print(type(Days))
print("looping through the set elements ... ")
for i in Days:
print(i)
输出:
{'Friday', 'Tuesday', 'Monday', 'Saturday', 'Thursday', 'Sunday', 'Wednesday'}
<class 'set'>
looping through the set elements ...
Friday
Tuesday
Monday
Saturday
Thursday
Sunday
Wednesday
使用 set() 方法创建集合
Days = set(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"])
print(Days)
print(type(Days))
print("looping through the set elements ... ")
for i in Days:
print(i)
输出:
{'Friday', 'Wednesday', 'Thursday', 'Saturday', 'Monday', 'Tuesday', 'Sunday'}
<class 'set'>
looping through the set elements ...
Friday
Wednesday
Thursday
Saturday
Monday
Tuesday
Sunday
它可以包含任何类型的元素,例如整数、浮点数、元组等。但是可变元素(列表、字典、集合)不能是集合的成员。考虑以下示例。
创建包含不可变元素的集合
# Creating a set which have immutable elements
set1 = {1,2,3, "JavaTpoint", 20.5, 14}
print(type(set1))
#Creating a set which have mutable element
set2 = {1,2,3,["Javatpoint",4]}
print(type(set2))
输出:
<class 'set'>
Traceback (most recent call last)
<ipython-input-5-9605bb6fbc68> in <module>
4
5 #Creating a set which holds mutable elements
----> 6 set2 = {1,2,3,["Javatpoint",4]}
7 print(type(set2))
TypeError: unhashable type: 'list'
在上面的代码中,我们创建了两个集合,集合 set1
包含不可变元素,而 set2
包含一个可变元素(列表)。在检查 set2
的类型时,引发了一个错误,这意味着集合只能包含不可变元素。
创建空集合有点不同,因为空的花括号 {}
也用于创建字典。因此,Python 提供了使用无参数的 set()
方法来创建空集合。
创建空集合
# Empty curly braces will create dictionary
set3 = {}
print(type(set3))
# Empty set using set() function
set4 = set()
print(type(set4))
输出:
<class 'dict'>
<class 'set'>
如果我们向集合提供重复的元素,看看会发生什么。
集合中的重复元素
set5 = {1,2,4,4,5,8,9,9,10}
print("Return set with unique elements:",set5)
输出:
Return set with unique elements: {1, 2, 4, 5, 8, 9, 10}
在上面的代码中,我们可以看到 set5
包含多个重复的元素,但在打印时会去除集合中的重复项。
向集合添加元素
Python 提供了 add()
方法和 update()
方法,用于向集合添加特定的项。add()
方法用于添加单个元素,而 update()
方法用于添加多个元素。
使用 add() 方法添加元素
Months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(months)
print("\nAdding other months to the set...");
Months.add("July");
Months.add ("August");
print("\nPrinting the modified set...");
print(Months)
print("\nlooping through the set elements ... ")
for i in Months:
print(i)
输出:
printing the original set ...
{'February', 'May', 'April', 'March', 'June', 'January'}
Adding other months to the set...
Printing the modified set...
{'February', 'July', 'May', 'April', 'March', 'August', 'June', 'January'}
looping through the set elements ...
February
July
May
April
March
August
June
January
使用 update() 方法添加多个元素
months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(months)
print("\nRemoving some months from the set...");
months.discard("January");
months.discard("May");
print("\nPrinting the modified set...");
print(months)
print("\nlooping through the set elements ... ")
for i in months:
print(i)
输出:
printing the original set ...
{'February', 'January', 'March', 'April', 'June', 'May'}
Removing some months from the set...
Printing the modified set...
{'February', 'March', 'April', 'June'}
looping through the set elements ...
February
March
April
June
从集合中删除元素
Python 提供了几种方法来从集合中删除元素。可以使用 remove()
、discard()
或 pop()
方法来执行此操作。
使用 remove() 方法删除元素
months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(months)
print("\nRemoving some months from the set...");
months.remove("January");
months.remove("May");
print("\nPrinting the modified set...");
print(months)
输出:
months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(months)
print("\nRemoving some months from the set...");
months.remove("January");
months.remove("May");
print("\nPrinting the modified set...");
print(months)
请注意,如果我们尝试删除不存在的元素,将引发错误。
使用 discard() 方法删除元素
months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(months)
print("\nRemoving some months from the set...");
months.discard("January");
months.discard("May");
print("\nPrinting the modified set...");
print(months)
print("\nlooping through the set elements ... ")
for i in months:
print(i)
输出:
printing the original set ...
{'February', 'January', 'March', 'April', 'June', 'May'}
Removing some months from the set...
Printing the modified set...
{'February', 'March', 'April', 'June'}
looping through the set elements ...
February
March
April
June
使用 pop() 方法删除元素
Months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(Months)
print("\nRemoving some months from the set...");
Months.pop();
Months.pop();
print("\nPrinting the modified set...");
print(Months)
输出:
printing the original set ...
{'June', 'January', 'May', 'April', 'February', 'March'}
Removing some months from the set...
Printing the modified set...
{'May', 'April', 'February', 'March'}
请注意,pop()
方法删除集合中的一个元素,但由于集合是无序的,因此无法预测删除的是哪个元素。
集合操作
Python 还提供了多种用于执行集合操作的内置方法,如并集、交集、差集等。
并集
可以使用 union()
方法或 |
运算符找到两个集合的并集。
# Create three sets
set1 = {1, 2, 3}
set2 = {2, 3, 4}
set3 = {3, 4, 5}
# Find the common elements between the three sets
common_elements = set1.union(set2, set3)
# Print the common elements
print(common_elements)
输出:
{1, 2, 3, 4, 5}
交集
可以使用 intersection()
方法或 &
运算符找到两个集合的交集。
# Create three sets
set1 = {1, 2, 3}
set2 = {2, 3, 4}
set3 = {3, 4, 5}
# Find the common elements between the three sets
common_elements = set1.intersection(set2, set3)
# Print the common elements
print(common_elements)
输出:
{3}
差集
可以使用 difference()
方法或 -
运算符找到两个集合的差集。
Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}
Days2 = {"Monday", "Tuesday", "Sunday"}
print(Days1.difference(Days2)) # prints the difference of the two sets Days1 and Days2
输出:
{'Thursday', 'Wednesday'}
对称差集
可以使用 symmetric_difference()
方法或 ^
运算符找到两个集合的对称差集(即只在一个集合中出现的元素)。
Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}
Days2 = {"Monday", "Tuesday"}
Days3 = {"Monday", "Tuesday", "Friday"}
#Days1 is the superset of Days2 hence it will print true.
print (Days1>Days2)
#prints false since Days1 is not the subset of Days2
print (Days1<Days2)
#prints false since Days2 and Days3 are not equivalent
print (Days2 == Days3)
输出:
True
False
False