В този урок ще научите всичко за наборите на Python; как се създават, добавяне или премахване на елементи от тях, както и всички операции, извършени върху набори в Python.
Видео: Комплекти в Python
Комплектът е неподредена колекция от предмети. Всеки зададен елемент е уникален (без дубликати) и трябва да бъде неизменяем (не може да се променя).
Самият набор обаче е променлив. Можем да добавяме или премахваме елементи от него.
Наборите могат да се използват и за извършване на операции с математически набор като обединение, пресичане, симетрична разлика и др.
Създаване на набори от Python
Набор се създава чрез поставяне на всички елементи (елементи) във фигурни скоби ()
, разделени със запетая или чрез използване на вградената set()
функция.
Той може да има произволен брой елементи и те могат да бъдат от различни типове (цяло число, плаващ, кортеж, низ и др.) Но набор не може да има променливи елементи като списъци, набори или речници като свои елементи.
# Different types of sets in Python # set of integers my_set = (1, 2, 3) print(my_set) # set of mixed datatypes my_set = (1.0, "Hello", (1, 2, 3)) print(my_set)
Изход
(1, 2, 3) (1.0, (1, 2, 3), „Здравейте“)
Опитайте и следните примери.
# set cannot have duplicates # Output: (1, 2, 3, 4) my_set = (1, 2, 3, 4, 3, 2) print(my_set) # we can make set from a list # Output: (1, 2, 3) my_set = set((1, 2, 3, 2)) print(my_set) # set cannot have mutable items # here (3, 4) is a mutable list # this will cause an error. my_set = (1, 2, (3, 4))
Изход
(1, 2, 3, 4) (1, 2, 3) Проследяване (последно последно обаждане): Файл "", ред 15, в my_set = (1, 2, (3, 4)) TypeError: unhashable type: "списък"
Създаването на празен набор е малко сложно.
Празни къдрави скоби ()
ще направят празен речник в Python. За да направим набор без никакви елементи, ние използваме set()
функцията без никакъв аргумент.
# Distinguish set and dictionary while creating empty set # initialize a with () a = () # check data type of a print(type(a)) # initialize a with set() a = set() # check data type of a print(type(a))
Изход
Модифициране на набор в Python
Комплектите са променливи. Тъй като обаче те са неподредени, индексирането няма значение.
Не можем да осъществим достъп или да променим елемент от набор, използвайки индексиране или нарязване. Зададеният тип данни не го поддържа.
Можем да добавим един елемент с помощта на add()
метода и множество елементи с помощта на update()
метода. В update()
метода може да се кортежи, списъци, низове или други си поставя за аргумент. Във всички случаи дубликатите се избягват.
# initialize my_set my_set = (1, 3) print(my_set) # my_set(0) # if you uncomment the above line # you will get an error # TypeError: 'set' object does not support indexing # add an element # Output: (1, 2, 3) my_set.add(2) print(my_set) # add multiple elements # Output: (1, 2, 3, 4) my_set.update((2, 3, 4)) print(my_set) # add list and set # Output: (1, 2, 3, 4, 5, 6, 8) my_set.update((4, 5), (1, 6, 8)) print(my_set)
Изход
(1, 3) (1, 2, 3) (1, 2, 3, 4) (1, 2, 3, 4, 5, 6, 8)
Премахване на елементи от набор
Определен елемент може да бъде премахнат от набор, използвайки методите discard()
и remove()
.
The only difference between the two is that the discard()
function leaves a set unchanged if the element is not present in the set. On the other hand, the remove()
function will raise an error in such a condition (if element is not present in the set).
The following example will illustrate this.
# Difference between discard() and remove() # initialize my_set my_set = (1, 3, 4, 5, 6) print(my_set) # discard an element # Output: (1, 3, 5, 6) my_set.discard(4) print(my_set) # remove an element # Output: (1, 3, 5) my_set.remove(6) print(my_set) # discard an element # not present in my_set # Output: (1, 3, 5) my_set.discard(2) print(my_set) # remove an element # not present in my_set # you will get an error. # Output: KeyError my_set.remove(2)
Output
(1, 3, 4, 5, 6) (1, 3, 5, 6) (1, 3, 5) (1, 3, 5) Traceback (most recent call last): File "", line 28, in KeyError: 2
Similarly, we can remove and return an item using the pop()
method.
Since set is an unordered data type, there is no way of determining which item will be popped. It is completely arbitrary.
We can also remove all the items from a set using the clear()
method.
# initialize my_set # Output: set of unique elements my_set = set("HelloWorld") print(my_set) # pop an element # Output: random element print(my_set.pop()) # pop another element my_set.pop() print(my_set) # clear my_set # Output: set() my_set.clear() print(my_set) print(my_set)
Output
('H', 'l', 'r', 'W', 'o', 'd', 'e') H ('r', 'W', 'o', 'd', 'e' ) комплект()
Операции за задаване на Python
Наборите могат да се използват за извършване на операции с математически набор като обединение, пресичане, разлика и симетрична разлика. Можем да направим това с оператори или методи.
Нека разгледаме следните два набора за следните операции.
>>> A = (1, 2, 3, 4, 5) >>> B = (4, 5, 6, 7, 8)
Set Union

Съединението на A и B е набор от всички елементи от двата набора.
Обединяването се извършва с помощта на |
оператор. Същото може да се постигне с помощта на union()
метода.
# Set union method # initialize A and B A = (1, 2, 3, 4, 5) B = (4, 5, 6, 7, 8) # use | operator # Output: (1, 2, 3, 4, 5, 6, 7, 8) print(A | B)
Изход
(1, 2, 3, 4, 5, 6, 7, 8)
Опитайте следните примери за обвивката на Python.
# use union function >>> A.union(B) (1, 2, 3, 4, 5, 6, 7, 8) # use union function on B >>> B.union(A) (1, 2, 3, 4, 5, 6, 7, 8)
Задайте пресичане

Пресичането на A и B е набор от елементи, които са често срещани и в двата множества.
Пресичането се извършва с помощта на &
оператор. Същото може да се постигне с помощта на intersection()
метода.
# Intersection of sets # initialize A and B A = (1, 2, 3, 4, 5) B = (4, 5, 6, 7, 8) # use & operator # Output: (4, 5) print(A & B)
Изход
(4, 5)
Опитайте следните примери за обвивката на Python.
# use intersection function on A >>> A.intersection(B) (4, 5) # use intersection function on B >>> B.intersection(A) (4, 5)
Задайте разлика

Разликата на множеството B от множеството A (A - B) е набор от елементи, които са само в A, но не и в B. По същия начин B - A е набор от елементи в B, но не и в A.
Разликата се извършва с помощта на -
оператор. Същото може да се постигне с помощта на difference()
метода.
# Difference of two sets # initialize A and B A = (1, 2, 3, 4, 5) B = (4, 5, 6, 7, 8) # use - operator on A # Output: (1, 2, 3) print(A - B)
Изход
(1, 2, 3)
Опитайте следните примери за обвивката на Python.
# use difference function on A >>> A.difference(B) (1, 2, 3) # use - operator on B >>> B - A (8, 6, 7) # use difference function on B >>> B.difference(A) (8, 6, 7)
Задайте симетрична разлика

Симетричната разлика на A и B е набор от елементи в A и B, но не и в двете (с изключение на пресечната точка).
Симетричната разлика се извършва с помощта на ^
оператор. Същото може да се постигне с помощта на метода symmetric_difference()
.
# Symmetric difference of two sets # initialize A and B A = (1, 2, 3, 4, 5) B = (4, 5, 6, 7, 8) # use operator # Output: (1, 2, 3, 6, 7, 8) print(A B)
Изход
(1, 2, 3, 6, 7, 8)
Опитайте следните примери за обвивката на Python.
# use symmetric_difference function on A >>> A.symmetric_difference(B) (1, 2, 3, 6, 7, 8) # use symmetric_difference function on B >>> B.symmetric_difference(A) (1, 2, 3, 6, 7, 8)
Други методи за задаване на Python
There are many set methods, some of which we have already used above. Here is a list of all the methods that are available with the set objects:
Method | Description |
---|---|
add() | Adds an element to the set |
clear() | Removes all elements from the set |
copy() | Returns a copy of the 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 the 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 |
pop() | Removes and returns an arbitrary set element. Raises KeyError if the set is empty |
remove() | Removes an element from the set. If the element is not a member, raises a KeyError |
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 |
union() | Returns the union of sets in a new set |
update() | Updates the set with the union of itself and others |
Other Set Operations
Set Membership Test
We can test if an item exists in a set or not, using the in
keyword.
# in keyword in a set # initialize my_set my_set = set("apple") # check if 'a' is present # Output: True print('a' in my_set) # check if 'p' is present # Output: False print('p' not in my_set)
Output
True False
Iterating Through a Set
We can iterate through each item in a set using a for
loop.
>>> for letter in set("apple"):… print(letter)… a p e l
Built-in Functions with Set
Built-in functions like all()
, any()
, enumerate()
, len()
, max()
, min()
, sorted()
, sum()
etc. are commonly used with sets to perform different tasks.
Function | Description |
---|---|
all() | Returns True if all elements of the set are true (or if the set is empty). |
any() | Returns True if any element of the set is true. If the set is empty, returns False . |
enumerate() | Returns an enumerate object. It contains the index and value for all the items of the set as a pair. |
len() | Returns the length (the number of items) in the set. |
max() | Returns the largest item in the set. |
min() | Returns the smallest item in the set. |
sorted() | Returns a new sorted list from elements in the set(does not sort the set itself). |
sum() | Returns the sum of all elements in the set. |
Python Frozenset
Frozenset е нов клас, който има характеристиките на набор, но неговите елементи не могат да бъдат променяни, след като бъдат присвоени. Докато кортежите са неизменни списъци, frozensets са неизменяеми набори.
Наборите, които могат да се променят, са неприемливи, така че не могат да се използват като речникови ключове. От друга страна, frozensets могат да се хашират и могат да се използват като ключове за речник.
Frozensets могат да бъдат създадени с помощта на функцията frozenset ().
Този тип данни подкрепят методи обичат copy()
, difference()
, intersection()
, isdisjoint()
, issubset()
, issuperset()
, symmetric_difference()
и union()
. Тъй като е неизменен, той няма методи, които добавят или премахват елементи.
# Frozensets # initialize A and B A = frozenset((1, 2, 3, 4)) B = frozenset((3, 4, 5, 6))
Опитайте тези примери за обвивката на Python.
>>> A.isdisjoint(B) False >>> A.difference(B) frozenset((1, 2)) >>> A | B frozenset((1, 2, 3, 4, 5, 6)) >>> A.add(3)… AttributeError: 'frozenset' object has no attribute 'add'