在 Python 中,Set是可迭代、可变且没有重复元素的数据类型的无序集合。集合中元素的顺序是不确定的,尽管它可能由各种元素组成。与列表相比,使用集合的主要优点是它具有高度优化的方法来检查特定元素是否包含在集合中。
可以通过将内置的set()函数与可迭代对象或序列一起使用来创建集合,方法是将序列放在花括号内,用“逗号”分隔。
注意:集合不能有像列表或字典这样的可变元素,因为它是可变的。
# Python program to demonstrate # Creation of Set in Python # Creating a Set set1 = set() print("Initial blank Set: ") print(set1) # Creating a Set with # the use of a String set1 = set("GeeksForGeeks") print("\nSet with the use of String: ") print(set1) # Creating a Set with # the use of Constructor # (Using object to Store String) String = 'GeeksForGeeks' set1 = set(String) print("\nSet with the use of an Object: " ) print(set1) # Creating a Set with # the use of a List set1 = set(["Geeks", "For", "Geeks"]) print("\nSet with the use of List: ") print(set1)
输出
Initial blank Set: set() Set with the use of String: {'r', 's', 'o', 'F', 'G', 'k', 'e'} Set with the use of an Object: {'r', 's', 'o', 'F', 'G', 'k', 'e'} Set with the use of List: {'For', 'Geeks'}
时间复杂度: O(n),其中 n 是输入字符串或列表的长度。 辅助空间: O(n),其中 n 是输入字符串或列表的长度,因为创建的集合的大小取决于输入的大小。
集合仅包含唯一元素,但在创建集合时,也可以传递多个重复值。集合中元素的顺序是未定义且不可更改的。集合中元素的类型不必相同,各种混合数据类型值也可以传递给集合。
# Creating a Set with # a List of Numbers # (Having duplicate values) set1 = set([1, 2, 4, 4, 3, 3, 3, 6, 5]) print("\nSet with the use of Numbers: ") print(set1) # Creating a Set with # a mixed type of values # (Having numbers and strings) set1 = set([1, 2, 'Geeks', 4, 'For', 6, 'Geeks']) print("\nSet with the use of Mixed Values") print(set1)
Set with the use of Numbers: {1, 2, 3, 4, 5, 6} Set with the use of Mixed Values {1, 2, 4, 6, 'Geeks', 'For'}
# Another Method to create sets in Python3 # Set containing numbers my_set = {1, 2, 3} print(my_set) # This code is contributed by sarajadhav12052009
{1, 2, 3}
可以使用内置的add()函数将元素添加到 Set 中。使用 add() 方法一次只能将一个元素添加到集合中,循环用于使用 add() 方法一次添加多个元素。
注意:列表不能作为元素添加到集合中,因为列表不可哈希,而元组可以添加,因为元组是不可变的,因此是可哈希的。
# Python program to demonstrate # Addition of elements in a Set # Creating a Set set1 = set() print("Initial blank Set: ") print(set1) # Adding element and tuple to the Set set1.add(8) set1.add(9) set1.add((6, 7)) print("\nSet after Addition of Three elements: ") print(set1) # Adding elements to the Set # using Iterator for i in range(1, 6): set1.add(i) print("\nSet after Addition of elements from 1-5: ") print(set1)
Initial blank Set: set() Set after Addition of Three elements: {8, 9, (6, 7)} Set after Addition of elements from 1-5: {1, 2, 3, (6, 7), 4, 5, 8, 9}
对于两个或多个元素的添加,使用 Update() 方法。update() 方法接受列表、字符串、元组以及其他集合作为其参数。在所有这些情况下,都避免了重复元素。
# Python program to demonstrate # Addition of elements in a Set # Addition of elements to the Set # using Update function set1 = set([4, 5, (6, 7)]) set1.update([10, 11]) print("\nSet after Addition of elements using Update: ") print(set1)
Set after Addition of elements using Update: {4, 5, (6, 7), 10, 11}
不能通过引用索引来访问集合项,因为集合是无序的,项没有索引。但是您可以使用 for 循环遍历集合项,或者使用 in 关键字询问集合中是否存在指定值。
# Python program to demonstrate # Accessing of elements in a set # Creating a set set1 = set(["Geeks", "For", "Geeks"]) print("\nInitial set") print(set1) # Accessing element using # for loop print("\nElements of set: ") for i in set1: print(i, end=" ") # Checking the element # using in keyword print("Geeks" in set1)
Initial set {'Geeks', 'For'} Elements of set: Geeks For True
可以使用内置的 remove() 函数从 Set 中删除元素,但如果集合中不存在该元素,则会出现 KeyError。要在没有 KeyError 的情况下从集合中删除元素,请使用 discard(),如果该元素不存在于集合中,它将保持不变。
# Python program to demonstrate # Deletion of elements in a Set # Creating a Set set1 = set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) print("Initial Set: ") print(set1) # Removing elements from Set # using Remove() method set1.remove(5) set1.remove(6) print("\nSet after Removal of two elements: ") print(set1) # Removing elements from Set # using Discard() method set1.discard(8) set1.discard(9) print("\nSet after Discarding two elements: ") print(set1) # Removing elements from Set # using iterator method for i in range(1, 5): set1.remove(i) print("\nSet after Removing a range of elements: ") print(set1)
Initial Set: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12} Set after Removal of two elements: {1, 2, 3, 4, 7, 8, 9, 10, 11, 12} Set after Discarding two elements: {1, 2, 3, 4, 7, 10, 11, 12} Set after Removing a range of elements: {7, 10, 11, 12}
Pop() 函数也可用于从集合中移除和返回元素,但它仅移除集合的最后一个元素。
注意:如果集合是无序的,则无法使用 pop() 函数确定弹出哪个元素。
# Python program to demonstrate # Deletion of elements in a Set # Creating a Set set1 = set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) print("Initial Set: ") print(set1) # Removing element from the # Set using the pop() method set1.pop() print("\nSet after popping an element: ") print(set1)
Initial Set: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12} Set after popping an element: {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}
要从集合中删除所有元素,使用 clear() 函数。
#Creating a set set1 = set([1,2,3,4,5]) print("\n Initial set: ") print(set1) # Removing all the elements from # Set using clear() method set1.clear() print("\nSet after clearing all the elements: ") print(set1)
Initial set: {1, 2, 3, 4, 5} Set after clearing all the elements: set()
Python 中的冻结集是不可变对象,它们只支持产生结果而不影响冻结集或应用它们的集合的方法和运算符。虽然可以随时修改集合的元素,但冻结集合的元素在创建后保持不变。
如果没有传递参数,它返回一个空的 frozenset。
# Python program to demonstrate # working of a FrozenSet # Creating a Set String = ('G', 'e', 'e', 'k', 's', 'F', 'o', 'r') Fset1 = frozenset(String) print("The FrozenSet is: ") print(Fset1) # To print Empty Frozen Set # No parameter is passed print("\nEmpty FrozenSet: ") print(frozenset())
The FrozenSet is: frozenset({'F', 's', 'o', 'G', 'r', 'e', 'k'}) Empty FrozenSet: frozenset()
# Typecasting Objects in Python3 into sets # Typecasting list into set my_list = [1, 2, 3, 3, 4, 5, 5, 6, 2] my_set = set(my_list) print("my_list as a set: ", my_set) # Typecasting string into set my_str = "GeeksforGeeks" my_set1 = set(my_str) print("my_str as a set: ", my_set1) # Typecasting dictionary into set my_dict = {1: "One", 2: "Two", 3: "Three"} my_set2 = set(my_dict) print("my_dict as a set: ", my_set2) # This code is contributed by sarajadhav12052009
my_list as a set: {1, 2, 3, 4, 5, 6} my_str as a set: {'G', 'f', 'r', 'e', 'k', 'o', 's'} my_dict as a set: {1, 2, 3}
def create_set(): my_set = {1, 2, 3, 4, 5} print(my_set) def add_element(): my_set = {1, 2, 3, 4, 5} my_set.add(6) print(my_set) def remove_element(): my_set = {1, 2, 3, 4, 5} my_set.remove(3) print(my_set) def clear_set(): my_set = {1, 2, 3, 4, 5} my_set.clear() print(my_set) def set_union(): set1 = {1, 2, 3} set2 = {4, 5, 6} my_set = set1.union(set2) print(my_set) def set_intersection(): set1 = {1, 2, 3, 4, 5} set2 = {4, 5, 6, 7, 8} my_set = set1.intersection(set2) print(my_set) def set_difference(): set1 = {1, 2, 3, 4, 5} set2 = {4, 5, 6, 7, 8} my_set = set1.difference(set2) print(my_set) def set_symmetric_difference(): set1 = {1, 2, 3, 4, 5} set2 = {4, 5, 6, 7, 8} my_set = set1.symmetric_difference(set2) print(my_set) def set_subset(): set1 = {1, 2, 3, 4, 5} set2 = {2, 3, 4} subset = set2.issubset(set1) print(subset) def set_superset(): set1 = {1, 2, 3, 4, 5} set2 = {2, 3, 4} superset = set1.issuperset(set2) print(superset) if __name__ == '__main__': create_set() add_element() remove_element() clear_set() set_union() set_intersection() set_difference() set_symmetric_difference() set_subset() set_superset()
{1, 2, 3, 4, 5} {1, 2, 3, 4, 5, 6} {1, 2, 4, 5} set() {1, 2, 3, 4, 5, 6} {4, 5} {1, 2, 3} {1, 2, 3, 6, 7, 8} True True
总的来说,集合在 Python 中是一种有用的数据结构,特别是对于删除重复项或快速成员资格测试。然而,它们缺乏顺序和有限的功能也使它们不如列表或字典通用,因此在决定在 Python 程序中使用哪种数据结构时,仔细考虑使用集合的优点和缺点很重要。
原文链接:codingdict.net