Zestaw Pythona (z przykładami)

W tym samouczku dowiesz się wszystkiego o zestawach Pythona; sposób ich tworzenia, dodawanie lub usuwanie z nich elementów oraz wszystkie operacje wykonywane na zestawach w Pythonie.

Wideo: zestawy w Pythonie

Zestaw to nieuporządkowana kolekcja przedmiotów. Każdy element zestawu jest niepowtarzalny (bez duplikatów) i musi być niezmienny (nie można go zmienić).

Jednak sam zestaw jest zmienny. Możemy dodawać lub usuwać z niego elementy.

Zbiory mogą być również używane do wykonywania matematycznych operacji na zbiorach, takich jak suma, przecięcie, różnica symetryczna itp.

Tworzenie zestawów w języku Python

Zestaw jest tworzony poprzez umieszczenie wszystkich elementów (elementów) w nawiasach klamrowych (), oddzielonych przecinkiem lub za pomocą funkcji wbudowanej set().

Może mieć dowolną liczbę elementów i mogą być różnych typów (liczba całkowita, zmiennoprzecinkowa, krotka, łańcuch itp.). Ale zestaw nie może mieć elementów zmiennych, takich jak listy, zbiory lub słowniki, jako jego elementy.

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

Wynik

 (1, 2, 3) (1.0, (1, 2, 3), 'Witaj')

Wypróbuj również poniższe przykłady.

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

Wynik

 (1, 2, 3, 4) (1, 2, 3) Traceback (ostatnie połączenie): Plik „”, wiersz 15, w my_set = (1, 2, (3, 4)) TypeError: unhashable type: 'lista'

Tworzenie pustego zestawu jest trochę trudne.

Puste nawiasy klamrowe ()utworzą pusty słownik w Pythonie. Aby utworzyć zestaw bez żadnych elementów, używamy set()funkcji bez żadnego argumentu.

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

Wynik

 

Modyfikacja zestawu w Pythonie

Zestawy są zmienne. Ponieważ jednak są one nieuporządkowane, indeksowanie nie ma znaczenia.

Nie możemy uzyskać dostępu do elementu zestawu ani go zmienić za pomocą indeksowania lub wycinania. Ustawiony typ danych nie obsługuje tego.

Możemy dodać pojedynczy element za pomocą add()metody, a wiele elementów za pomocą update()metody. update()Metoda może krotki, listy, sznurki lub inne zestawy jako argument. We wszystkich przypadkach unika się duplikatów.

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

Wynik

 (1, 3) (1, 2, 3) (1, 2, 3, 4) (1, 2, 3, 4, 5, 6, 8)

Usuwanie elementów z zestawu

Poszczególną pozycję można usunąć z zestawu za pomocą metod discard()i remove().

Jedyna różnica między nimi polega na tym, że discard()funkcja pozostawia zestaw niezmieniony, jeśli element nie jest obecny w zestawie. Z drugiej strony remove()funkcja zgłosi błąd w takim stanie (jeśli w zbiorze nie ma elementu).

Zilustruje to poniższy przykład.

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

Wynik

 (1, 3, 4, 5, 6) (1, 3, 5, 6) (1, 3, 5) (1, 3, 5) Traceback (ostatnie ostatnie połączenie): Plik „”, wiersz 28, w KeyError: 2

Podobnie możemy usunąć i zwrócić przedmiot za pomocą pop()metody.

Ponieważ set jest nieuporządkowanym typem danych, nie ma możliwości określenia, który element zostanie pobrany. Jest to całkowicie arbitralne.

Możemy również usunąć wszystkie pozycje z zestawu clear()metodą.

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

Wynik

 ('H', 'l', 'r', 'W', 'o', 'd', 'e') H ('r', 'W', 'o', 'd', 'e' ) zestaw ()

Operacje na zbiorach w Pythonie

Zbiory mogą być używane do wykonywania matematycznych operacji na zbiorach, takich jak suma, przecięcie, różnica i różnica symetryczna. Możemy to zrobić za pomocą operatorów lub metod.

Rozważmy następujące dwa zbiory dla następujących operacji.

 >>> A = (1, 2, 3, 4, 5) >>> B = (4, 5, 6, 7, 8)

Ustaw Union

Ustaw Union w Pythonie

Suma A i B to zbiór wszystkich elementów z obu zbiorów.

Suma jest wykonywana za pomocą |operatora. To samo można osiągnąć za pomocą union()metody.

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

Wynik

 (1, 2, 3, 4, 5, 6, 7, 8)

Wypróbuj następujące przykłady w powłoce Pythona.

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

Ustaw przecięcie

Ustaw przecięcie w Pythonie

Przecięcie A i B to zbiór elementów, które są wspólne w obu zestawach.

Przecięcie jest wykonywane za pomocą &operatora. To samo można osiągnąć za pomocą intersection()metody.

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

Wynik

 (4, 5)

Wypróbuj następujące przykłady w powłoce Pythona.

 # use intersection function on A >>> A.intersection(B) (4, 5) # use intersection function on B >>> B.intersection(A) (4, 5)

Ustaw różnicę

Ustaw różnicę w Pythonie

Różnica zbioru B od zbioru A (A - B) to zbiór elementów, które są tylko w A, ale nie w B. Podobnie B - A to zbiór elementów w B, ale nie w A.

Różnica jest wykonywana za pomocą -operatora. To samo można osiągnąć za pomocą difference()metody.

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

Wynik

 (1, 2, 3)

Wypróbuj następujące przykłady w powłoce Pythona.

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

Ustaw różnicę symetryczną

Ustaw różnicę symetryczną w Pythonie

Różnica symetryczna A i B to zbiór elementów w A i B, ale nie w obu (z wyłączeniem przecięcia).

Różnica symetryczna jest wykonywana za pomocą ^operatora. To samo można osiągnąć za pomocą metody 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)

Wynik

 (1, 2, 3, 6, 7, 8)

Wypróbuj następujące przykłady w powłoce Pythona.

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

Inne metody zestawu Pythona

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 to nowa klasa, która ma cechy zbioru, ale po przypisaniu jej elementów nie można zmienić. Podczas gdy krotki są niezmiennymi listami, zestawy zamrożone są niezmiennymi zestawami.

Zestawy, które są mutowalne, nie są haszowane, więc nie mogą być używane jako klucze słownika. Z drugiej strony zestawy zamrożone są hashowane i mogą być używane jako klucze do słownika.

Frozensets można tworzyć za pomocą funkcji frozenset ().

Ten typ danych metody podpory podoba copy(), difference(), intersection(), isdisjoint(), issubset(), issuperset(), symmetric_difference()i union(). Będąc niezmiennym, nie ma metod, które dodają lub usuwają elementy.

 # Frozensets # initialize A and B A = frozenset((1, 2, 3, 4)) B = frozenset((3, 4, 5, 6))

Wypróbuj te przykłady w powłoce Pythona.

 >>> 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'

Interesujące artykuły...