În acest tutorial, veți afla totul despre seturile Python; cum sunt create, adăugând sau eliminând elemente din ele și toate operațiunile efectuate pe seturi în Python.
Video: Setează în Python
Un set este o colecție neordonată de articole. Fiecare element set este unic (fără duplicate) și trebuie să fie imuabil (nu poate fi modificat).
Cu toate acestea, un set în sine este mutabil. Putem adăuga sau elimina articole din acesta.
Seturile pot fi, de asemenea, utilizate pentru a efectua operații matematice de seturi, cum ar fi unirea, intersecția, diferența simetrică etc.
Crearea seturilor Python
Un set este creat prin plasarea tuturor elementelor (elementelor) în interiorul acoladelor ()
, separate prin virgulă sau utilizând funcția încorporată set()
.
Poate avea orice număr de articole și pot fi de diferite tipuri (număr întreg, float, tuplu, șir etc.). Dar un set nu poate avea ca elemente elemente mutabile precum liste, seturi sau dicționare.
# 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)
Ieșire
(1, 2, 3) (1.0, (1, 2, 3), „Bună ziua”)
Încercați și următoarele exemple.
# 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))
Ieșire
(1, 2, 3, 4) (1, 2, 3) Traceback (ultimul apel cel mai recent): Fișierul "", linia 15, în setul_meu = (1, 2, (3, 4)) Tip Eroare: tip unihable: 'listă'
Crearea unui set gol este cam dificilă.
Aparatele dentare goale ()
vor crea un dicționar gol în Python. Pentru a crea un set fără elemente, folosim set()
funcția fără niciun argument.
# 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))
Ieșire
Modificarea unui set în Python
Seturile pot fi modificate. Cu toate acestea, deoarece acestea sunt neordonate, indexarea nu are nici un sens.
Nu putem accesa sau modifica un element al unui set folosind indexarea sau felierea. Setarea tipului de date nu o acceptă.
Putem adăuga un singur element folosind add()
metoda și mai multe elemente folosind update()
metoda. update()
Metoda poate lua tupluri, liste, siruri de caractere sau alte seturi ca argument. În toate cazurile, duplicatele sunt evitate.
# 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)
Ieșire
(1, 3) (1, 2, 3) (1, 2, 3, 4) (1, 2, 3, 4, 5, 6, 8)
Eliminarea elementelor dintr-un set
Un anumit element poate fi eliminat dintr-un set folosind metodele discard()
și remove()
.
Singura diferență dintre cele două este că discard()
funcția lasă un set neschimbat dacă elementul nu este prezent în set. Pe de altă parte, remove()
funcția va ridica o eroare într-o astfel de condiție (dacă elementul nu este prezent în set).
Următorul exemplu va ilustra acest lucru.
# 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)
Ieșire
(1, 3, 4, 5, 6) (1, 3, 5, 6) (1, 3, 5) (1, 3, 5) Traceback (ultimul apel ultim): Fișierul "", linia 28, în KeyError: 2
În mod similar, putem elimina și returna un articol folosind pop()
metoda.
Deoarece setul este un tip de date neordonat, nu există nicio modalitate de a determina ce element va fi afișat. Este complet arbitrar.
De asemenea, putem elimina toate articolele dintr-un set folosind clear()
metoda.
# 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)
Ieșire
('H', 'l', 'r', 'W', 'o', 'd', 'e') H ('r', 'W', 'o', 'd', 'e' ) a stabilit()
Operații de setare Python
Seturile pot fi utilizate pentru a efectua operații de seturi matematice, cum ar fi unirea, intersecția, diferența și diferența simetrică. Putem face acest lucru cu operatori sau metode.
Să luăm în considerare următoarele două seturi pentru următoarele operații.
>>> A = (1, 2, 3, 4, 5) >>> B = (4, 5, 6, 7, 8)
Set Unire

Uniunea dintre A și B este un set de elemente din ambele seturi.
Unirea se realizează cu ajutorul |
operatorului. Același lucru poate fi realizat folosind union()
metoda.
# 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)
Ieșire
(1, 2, 3, 4, 5, 6, 7, 8)
Încercați următoarele exemple pe Python shell.
# 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)
Setați intersecția

Intersecția lui A și B este un set de elemente care sunt comune în ambele seturi.
Intersecția se efectuează cu ajutorul &
operatorului. Același lucru poate fi realizat folosind intersection()
metoda.
# 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)
Ieșire
(4, 5)
Încercați următoarele exemple pe Python shell.
# use intersection function on A >>> A.intersection(B) (4, 5) # use intersection function on B >>> B.intersection(A) (4, 5)
Stabiliți diferența

Diferența mulțimii B față de mulțimea A (A - B) este un set de elemente care sunt doar în A, dar nu în B. În mod similar, B - A este un set de elemente în B, dar nu în A.
Diferența se realizează folosind -
operatorul. Același lucru poate fi realizat folosind difference()
metoda.
# 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)
Ieșire
(1, 2, 3)
Încercați următoarele exemple pe Python shell.
# 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)
Setați diferența simetrică

Diferența simetrică a lui A și B este un set de elemente în A și B, dar nu în ambele (cu excepția intersecției).
Diferența simetrică se realizează folosind ^
operatorul. Același lucru poate fi realizat folosind metoda 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)
Ieșire
(1, 2, 3, 6, 7, 8)
Încercați următoarele exemple pe Python shell.
# 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)
Alte metode de setare 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 este o nouă clasă care are caracteristicile unui set, dar elementele sale nu pot fi schimbate odată atribuite. În timp ce tuplurile sunt liste imuabile, frozensets sunt seturi imuabile.
Seturile care pot fi modificate sunt unihable, deci nu pot fi utilizate ca chei de dicționar. Pe de altă parte, seturile frozens sunt lavabile și pot fi folosite ca chei ale unui dicționar.
Frozenseturile pot fi create folosind funcția frozenset ().
Acest tip de date metode de suporturi ca copy()
, difference()
, intersection()
, isdisjoint()
, issubset()
, issuperset()
, symmetric_difference()
și union()
. Fiind imuabil, nu are metode care să adauge sau să elimine elemente.
# Frozensets # initialize A and B A = frozenset((1, 2, 3, 4)) B = frozenset((3, 4, 5, 6))
Încercați aceste exemple pe shell-ul 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'