📜  Python集

📅  最后修改于: 2022-05-13 01:54:44.390000             🧑  作者: Mango

Python集

在Python中, Set是数据类型的无序集合,它是可迭代的、可变的并且没有重复元素。集合中元素的顺序是不确定的,尽管它可能由各种元素组成。

与列表相比,使用集合的主要优点是它具有高度优化的方法来检查集合中是否包含特定元素。

创建一个集合

可以通过使用带有可迭代对象或序列的内置set()函数来创建集合,方法是将序列放在花括号内,用“逗号”分隔。

注意 –集合不能具有可变元素,如列表或字典,因为它是可变的。

Python3
# 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)


Python3
# 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)


Python3
# 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)


Python3
# 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)


Python3
# 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)


Python3
# 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)


Python3
# 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)


Python3
#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)


Python3
# 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())


输出:

Initial blank Set: 
set()

Set with the use of String: 
{'e', 'r', 'k', 'o', 'G', 's', 'F'}

Set with the use of an Object: 
{'r', 'o', 'e', 'F', 's', 'k', 'G'}

Set with the use of List: 
{'Geeks', 'For'}

集合仅包含唯一元素,但在创建集合时,也可以传递多个重复值。集合中元素的顺序未定义且不可更改。集合中元素的类型不必相同,也可以将各种混合的数据类型值传递给集合。

Python3

# 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, 'Geeks', 6, 'For'}

将元素添加到集合

使用 add() 方法

可以使用内置的add()函数将元素添加到 Set 中。使用 add() 方法一次只能将一个元素添加到集合中,循环用于使用 add() 方法一次添加多个元素。

注意 –不能将列表作为元素添加到集合中,因为列表不可散列,而可以添加元组,因为元组是不可变的,因此可以散列。

Python3

# 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() 方法。 update() 方法接受列表、字符串、元组以及其他集合作为其参数。在所有这些情况下,都避免了重复元素。

Python3

# 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: 
{10, 11, 4, 5, (6, 7)}
 

访问集合

集合项不能通过引用索引来访问,因为集合是无序的,这些项没有索引。但是您可以使用 for 循环遍历集合项,或者使用 in 关键字询问集合中是否存在指定值。

Python3

# 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() 方法或 discard() 方法

可以使用内置的 remove()函数从集合中删除元素,但如果集合中不存在元素,则会出现 KeyError。要从没有 KeyError 的集合中删除元素,请使用 discard(),如果集合中不存在该元素,则它保持不变。

Python3

# 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()函数也可用于从集合中移除并返回一个元素,但它只移除集合的最后一个元素。
注意 –如果集合是无序的,则无法使用 pop()函数确定弹出哪个元素。

Python3

# 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() 方法

要从集合中删除所有元素,请使用 clear()函数。

Python3

#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。

Python3

# 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())

设置方法

FunctionDescription
add()Adds an element to a set
remove()Removes an element from a set. If the element is not present in the set, raise a KeyError
clear()Removes all elements form a set
copy()Returns a shallow copy of a set
pop()Removes and returns an arbitrary set element. Raise KeyError if the set is empty
update()Updates a set with the union of itself and others
union()Returns the union of sets in a new set
difference()Returns the difference of two or more sets as a new set
difference_update()Removes all elements of another set from this set
discard()Removes an element from set if it is a member. (Do nothing if the element is not in set)
intersection()Returns the intersection of two sets as a new set
intersection_update()Updates the set with the intersection of itself and another
isdisjoint()Returns True if two sets have a null intersection
issubset()Returns True if another set contains this set
issuperset()Returns True if this set contains another set
symmetric_difference()Returns the symmetric difference of two sets as a new set
symmetric_difference_update()Updates a set with the symmetric difference of itself and another

最近关于Python集的文章

设置程序

  • 接受包含所有元音的字符串的程序
  • 使用集合在三个列表中查找共同元素的Python程序
  • 在两个列表中查找缺失值和附加值
  • 两组成对的完整字符串
  • 检查给定字符串是否为 Heterogram
  • 集合中的最大值和最小值
  • 从集合中移除项目
  • Python设置差异以从重复数组中查找丢失的元素
  • 使用 Counter 的具有不同元素的最小子集数
  • 检查两个列表是否至少有一个共同元素
  • 使用给定字符串中的集合计算元音数量的程序
  • 两个列表之间的区别
  • Python设置检查字符串是否是panagram
  • Python集合操作(并、交、差和对称差)
  • Python中具有不常见字符的连接字符串
  • Python字典,设置和计数器来检查频率是否可以变得相同
  • 在Python Pangram 检查中使用 Set()
  • 在Python中设置 update() 来合并 n 个数组

有用的链接

  • Python程序的输出——集合
  • 最近关于Python集的文章
  • 多项选择题 - Python
  • Python分类中的所有文章