📜  Python中的集合

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

Python中的集合

Set 是一种可迭代、可变且没有重复元素的无序集合数据类型。 Python 的集合类表示集合的数学概念。与列表相比,使用集合的主要优点是它具有高度优化的方法来检查集合中是否包含特定元素。这是基于称为哈希表的数据结构。由于集合是无序的,我们不能像在列表中那样使用索引来访问项目。

Python3
# Python program to
# demonstrate sets
 
# Same as {"a", "b", "c"}
myset = set(["a", "b", "c"])
print(myset)
 
# Adding element to the set
myset.add("d")
print(myset)


Python
# Python program to demonstrate differences
# between normal and frozen set
 
# Same as {"a", "b","c"}
normal_set = set(["a", "b","c"])
 
print("Normal Set")
print(normal_set)
 
# A frozen set
frozen_set = frozenset(["e", "f", "g"])
 
print("\nFrozen Set")
print(frozen_set)
 
# Uncommenting below line would cause error as
# we are trying to add element to a frozen set
# frozen_set.add("h")


Python3
# A Python program to
# demonstrate adding elements
# in a set
 
# Creating a Set
people = {"Jay", "Idrish", "Archi"}
 
print("People:", end = " ")
print(people)
 
# This will add Daxit
# in the set
people.add("Daxit")
 
# Adding elements to the
# set using iterator
for i in range(1, 6):
    people.add(i)
 
print("\nSet after adding element:", end = " ")
print(people)


Python3
# Python Program to
# demonstrate union of
# two sets
 
people = {"Jay", "Idrish", "Archil"}
vampires = {"Karan", "Arjun"}
dracula = {"Deepanshu", "Raju"}
 
# Union using union()
# function
population = people.union(vampires)
 
print("Union using union() function")
print(population)
 
# Union using "|"
# operator
population = people|dracula
 
print("\nUnion using '|' operator")
print(population)


Python3
# Python program to
# demonstrate intersection
# of two sets
 
set1 = set()
set2 = set()
 
for i in range(5):
    set1.add(i)
 
for i in range(3,9):
    set2.add(i)
 
# Intersection using
# intersection() function
set3 = set1.intersection(set2)
 
print("Intersection using intersection() function")
print(set3)
 
# Intersection using
# "&" operator
set3 = set1 & set2
 
print("\nIntersection using '&' operator")
print(set3)


Python3
# Python program to
# demonstrate difference
# of two sets
 
set1 = set()
set2 = set()
 
for i in range(5):
    set1.add(i)
 
for i in range(3,9):
    set2.add(i)
 
# Difference of two sets
# using difference() function
set3 = set1.difference(set2)
 
print(" Difference of two sets using difference() function")
print(set3)
 
# Difference of two sets
# using '-' operator
set3 = set1 - set2
 
print("\nDifference of two sets using '-' operator")
print(set3)


Python3
# Python program to
# demonstrate clearing
# of set
 
set1 = {1,2,3,4,5,6}
 
print("Initial set")
print(set1)
 
# This method will remove
# all the elements of the set
set1.clear()
 
print("\nSet after using clear() function")
print(set1)


Python
# Python program to demonstrate working# of
# Set in Python
 
# Creating two sets
set1 = set()
set2 = set()
 
# Adding elements to set1
for i in range(1, 6):
    set1.add(i)
 
# Adding elements to set2
for i in range(3, 8):
    set2.add(i)
 
print("Set1 = ", set1)
print("Set2 = ", set2)
print("\n")
 
# Union of set1 and set2
set3 = set1 | set2# set1.union(set2)
print("Union of Set1 & Set2: Set3 = ", set3)
 
# Intersection of set1 and set2
set4 = set1 & set2# set1.intersection(set2)
print("Intersection of Set1 & Set2: Set4 = ", set4)
print("\n")
 
# Checking relation between set3 and set4
if set3 > set4: # set3.issuperset(set4)
    print("Set3 is superset of Set4")
else if set3 < set4: # set3.issubset(set4)
    print("Set3 is subset of Set4")
else : # set3 == set4
    print("Set3 is same as Set4")
 
# displaying relation between set4 and set3
if set4 < set3: # set4.issubset(set3)
    print("Set4 is subset of Set3")
    print("\n")
 
# difference between set3 and set4
set5 = set3 - set4
print("Elements in Set3 and not in Set4: Set5 = ", set5)
print("\n")
 
# check if set4 and set5 are disjoint sets
if set4.isdisjoint(set5):
    print("Set4 and Set5 have nothing in common\n")
 
# Removing all the values of set5
set5.clear()
 
print("After applying clear on sets Set5: ")
print("Set5 = ", set5)


输出:
{'c', 'b', 'a'}
{'d', 'c', 'b', 'a'}

冷冻套装

Python中的冻结集是不可变对象,仅支持产生结果而不影响应用它们的冻结集的方法和运算符。虽然集合的元素可以随时修改,但冻结集合的元素在创建后保持不变。
如果没有传递参数,则返回一个空的frozenset。

Python

# Python program to demonstrate differences
# between normal and frozen set
 
# Same as {"a", "b","c"}
normal_set = set(["a", "b","c"])
 
print("Normal Set")
print(normal_set)
 
# A frozen set
frozen_set = frozenset(["e", "f", "g"])
 
print("\nFrozen Set")
print(frozen_set)
 
# Uncommenting below line would cause error as
# we are trying to add element to a frozen set
# frozen_set.add("h")
输出:
Normal Set
set(['a', 'c', 'b'])

Frozen Set
frozenset(['e', 'g', 'f'])

Set的内部工作

这是基于称为哈希表的数据结构。
如果多个值存在于同一索引位置,则将该值附加到该索引位置,以形成链接列表。在其中, Python集是使用带有虚拟变量的字典来实现的,其中关键是成员集,对时间复杂度进行了更大的优化。
设置实施:-

在单个 HashTable 上设置许多操作:-

集合的方法

添加元素

set 中的插入是通过 set.add()函数完成的,其中创建了一个适当的记录值以存储在哈希表中。与检查项目相同,即平均 O(1)。但是,在最坏的情况下,它可能会变成 O(n)。

Python3

# A Python program to
# demonstrate adding elements
# in a set
 
# Creating a Set
people = {"Jay", "Idrish", "Archi"}
 
print("People:", end = " ")
print(people)
 
# This will add Daxit
# in the set
people.add("Daxit")
 
# Adding elements to the
# set using iterator
for i in range(1, 6):
    people.add(i)
 
print("\nSet after adding element:", end = " ")
print(people)
输出:
People: {'Idrish', 'Archi', 'Jay'}

Set after adding element: {1, 2, 3, 4, 5, 'Idrish', 'Archi', 'Jay', 'Daxit'}

联盟

可以使用 union()函数或 | 合并两个集合运算符。访问和遍历这两个哈希表值,并对它们执行合并操作以组合元素,同时删除重复项。其时间复杂度为 O(len(s1) + len(s2)),其中 s1 和 s2 是需要合并的两个集合。

Python3

# Python Program to
# demonstrate union of
# two sets
 
people = {"Jay", "Idrish", "Archil"}
vampires = {"Karan", "Arjun"}
dracula = {"Deepanshu", "Raju"}
 
# Union using union()
# function
population = people.union(vampires)
 
print("Union using union() function")
print(population)
 
# Union using "|"
# operator
population = people|dracula
 
print("\nUnion using '|' operator")
print(population)
输出:
Union using union() function
{'Karan', 'Idrish', 'Jay', 'Arjun', 'Archil'}

Union using '|' operator
{'Deepanshu', 'Idrish', 'Jay', 'Raju', 'Archil'}

路口

这可以通过 intersection() 或 &运算符来完成。公共元素被选中。它们类似于对哈希列表的迭代并在两个表上组合相同的值。其时间复杂度为 O(min(len(s1), len(s2)),其中 s1 和 s2 是需要合并的两个集合。

Python3

# Python program to
# demonstrate intersection
# of two sets
 
set1 = set()
set2 = set()
 
for i in range(5):
    set1.add(i)
 
for i in range(3,9):
    set2.add(i)
 
# Intersection using
# intersection() function
set3 = set1.intersection(set2)
 
print("Intersection using intersection() function")
print(set3)
 
# Intersection using
# "&" operator
set3 = set1 & set2
 
print("\nIntersection using '&' operator")
print(set3)
输出:
Intersection using intersection() function
{3, 4}

Intersection using '&' operator
{3, 4}

不同之处

找出组之间的差异。类似于在链表中查找差异。这是通过 difference() 或 – 运算符完成的。求差 s1 – s2 的时间复杂度为 O(len(s1))

Python3

# Python program to
# demonstrate difference
# of two sets
 
set1 = set()
set2 = set()
 
for i in range(5):
    set1.add(i)
 
for i in range(3,9):
    set2.add(i)
 
# Difference of two sets
# using difference() function
set3 = set1.difference(set2)
 
print(" Difference of two sets using difference() function")
print(set3)
 
# Difference of two sets
# using '-' operator
set3 = set1 - set2
 
print("\nDifference of two sets using '-' operator")
print(set3)
输出:
Difference of two sets using difference() function
{0, 1, 2}

Difference of two sets using '-' operator
{0, 1, 2}

清算集

Clear() 方法清空整个集合。

Python3

# Python program to
# demonstrate clearing
# of set
 
set1 = {1,2,3,4,5,6}
 
print("Initial set")
print(set1)
 
# This method will remove
# all the elements of the set
set1.clear()
 
print("\nSet after using clear() function")
print(set1)
输出:
Initial set
{1, 2, 3, 4, 5, 6}

Set after using clear() function
set()

但是, Python集合中有两个主要缺陷:

  1. 该集合不以任何特定顺序维护元素。
  2. 只有不可变类型的实例才能添加到Python集中。

集合的时间复杂度

OperationAverage caseWorst Casenotes
x in sO(1)O(n) 
Union s|tO(len(s)+len(t))  
Intersection s&tO(min(len(s), len(t))O(len(s) * len(t))replace “min” with “max” if t is not a set
Multiple intersection s1&s2&..&sn (n-1)*O(l) where l is max(len(s1),..,len(sn)) 
Difference s-tO(len(s))  

集合的运算符

集合和冻结集合支持以下运算符:

OperatorsNotes
key in scontainment check
key not in snon-containment check
s1 == s2s1 is equivalent to s2
s1 != s2s1 is not equivalent to s2
s1 <= s2s1 is subset of s2
s1 < s2s1 is proper subset of s2
s1 >= s2s1 is superset of s2
s1 > s2s1 is proper superset of s2
s1 | s2the union of s1 and s2
s1 & s2the intersection of s1 and s2
s1 – s2the set of elements in s1 but not s2
s1 ˆ s2the set of elements in precisely one of s1 or s2

说明Python中所有 Set 操作的代码片段

Python

# Python program to demonstrate working# of
# Set in Python
 
# Creating two sets
set1 = set()
set2 = set()
 
# Adding elements to set1
for i in range(1, 6):
    set1.add(i)
 
# Adding elements to set2
for i in range(3, 8):
    set2.add(i)
 
print("Set1 = ", set1)
print("Set2 = ", set2)
print("\n")
 
# Union of set1 and set2
set3 = set1 | set2# set1.union(set2)
print("Union of Set1 & Set2: Set3 = ", set3)
 
# Intersection of set1 and set2
set4 = set1 & set2# set1.intersection(set2)
print("Intersection of Set1 & Set2: Set4 = ", set4)
print("\n")
 
# Checking relation between set3 and set4
if set3 > set4: # set3.issuperset(set4)
    print("Set3 is superset of Set4")
else if set3 < set4: # set3.issubset(set4)
    print("Set3 is subset of Set4")
else : # set3 == set4
    print("Set3 is same as Set4")
 
# displaying relation between set4 and set3
if set4 < set3: # set4.issubset(set3)
    print("Set4 is subset of Set3")
    print("\n")
 
# difference between set3 and set4
set5 = set3 - set4
print("Elements in Set3 and not in Set4: Set5 = ", set5)
print("\n")
 
# check if set4 and set5 are disjoint sets
if set4.isdisjoint(set5):
    print("Set4 and Set5 have nothing in common\n")
 
# Removing all the values of set5
set5.clear()
 
print("After applying clear on sets Set5: ")
print("Set5 = ", set5)
输出:
('Set1 = ', set([1, 2, 3, 4, 5]))
('Set2 = ', set([3, 4, 5, 6, 7]))


('Union of Set1 & Set2: Set3 = ', set([1, 2, 3, 4, 5, 6, 7]))
('Intersection of Set1 & Set2: Set4 = ', set([3, 4, 5]))


Set3 is superset of Set4
Set4 is subset of Set3


('Elements in Set3 and not in Set4: Set5 = ', set([1, 2, 6, 7]))


Set4 and Set5 have nothing in common

After applying clear on sets Set5: 
('Set5 = ', set([]))

最近关于Python集的文章。