Python-set (med exempel)

I den här handledningen lär du dig allt om Python-set; hur de skapas, lägga till eller ta bort element från dem och alla åtgärder som utförs på uppsättningar i Python.

Video: Uppsättningar i Python

En uppsättning är en oordnad samling objekt. Varje uppsättningselement är unikt (inga dubbletter) och måste vara oföränderligt (kan inte ändras).

En uppsättning i sig är emellertid muterbar. Vi kan lägga till eller ta bort objekt från den.

Uppsättningar kan också användas för att utföra matematiska uppsättningsoperationer som koppling, korsning, symmetrisk skillnad etc.

Skapa Python-uppsättningar

En uppsättning skapas genom att placera alla föremål (element) inuti lockiga hakparenteser (), åtskilda med komma eller genom att använda den inbyggda set()funktionen.

Det kan ha valfritt antal objekt och de kan vara av olika typer (heltal, float, tuple, sträng etc.). Men en uppsättning kan inte ha muterbara element som listor, uppsättningar eller ordböcker som dess element.

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

Produktion

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

Prova också följande exempel.

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

Produktion

 (1, 2, 3, 4) (1, 2, 3) Spårning (senaste samtalet senast): Fil "", rad 15, i min_uppsättning = (1, 2, (3, 4)) TypFel: otänkbar typ: 'lista'

Att skapa en tom uppsättning är lite knepigt.

Tomma lockiga hängslen ()gör en tom ordbok i Python. För att göra en uppsättning utan några element använder vi set()funktionen utan 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))

Produktion

 

Ändra en uppsättning i Python

Uppsättningarna är mutabla. Men eftersom de inte är ordnade har indexering ingen betydelse.

Vi kan inte komma åt eller ändra ett element i en uppsättning med hjälp av indexering eller skivning. Ange datatyp stöder inte den.

Vi kan lägga till ett enda element med add()metoden och flera element med update()metoden. Den update()metod kan ta tupler, listor, strängar eller andra uppsättningar som dess argument. I alla fall undviks dubbletter.

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

Produktion

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

Ta bort element från en uppsättning

Ett visst objekt kan tas bort från en uppsättning med metoderna discard()och remove().

Den enda skillnaden mellan de två är att discard()funktionen lämnar en uppsättning oförändrad om elementet inte finns i uppsättningen. Å andra sidan kommer remove()funktionen att ge upp ett fel i ett sådant tillstånd (om element inte finns i uppsättningen).

Följande exempel illustrerar detta.

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

Produktion

 (1, 3, 4, 5, 6) (1, 3, 5, 6) (1, 3, 5) (1, 3, 5) Spårning (senaste samtalet senast): Fil "", rad 28, i KeyError: 2

På samma sätt kan vi ta bort och returnera ett objekt med pop()metoden.

Eftersom set är en oordnad datatyp finns det inget sätt att avgöra vilket objekt som ska poppas. Det är helt godtyckligt.

Vi kan också ta bort alla objekt från en uppsättning med clear()metoden.

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

Produktion

 ('H', 'l', 'r', 'W', 'o', 'd', 'e') H ('r', 'W', 'o', 'd', 'e' ) uppsättning()

Python Set-funktioner

Uppsättningar kan användas för att utföra matematiska uppsättningsoperationer som fack, korsning, skillnad och symmetrisk skillnad. Vi kan göra detta med operatörer eller metoder.

Låt oss överväga följande två uppsättningar för följande operationer.

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

Ställ in Union

Ställ Union i Python

Union av A och B är en uppsättning av alla element från båda uppsättningarna.

Union utförs med |operatör. Samma kan uppnås med union()metoden.

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

Produktion

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

Prova följande exempel på Python-skal.

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

Ställ in korsningen

Ställ in korsningen i Python

Skärningspunkten mellan A och B är en uppsättning element som är vanliga i båda uppsättningarna.

Korsningen utförs med &operatören. Samma kan uppnås med intersection()metoden.

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

Produktion

 (4, 5)

Prova följande exempel på Python-skal.

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

Ställ in skillnad

Ställ in skillnad i Python

Skillnad mellan uppsättning B från uppsättning A (A - B) är en uppsättning element som bara finns i A men inte i B. På samma sätt är B - A en uppsättning element i B men inte i A.

Skillnaden utförs med -operatören. Samma kan uppnås med difference()metoden.

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

Produktion

 (1, 2, 3)

Prova följande exempel på Python-skal.

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

Ställ in symmetrisk skillnad

Ställ in symmetrisk skillnad i Python

Symmetrisk skillnad mellan A och B är en uppsättning element i A och B men inte i båda (exklusive korsningen).

Symmetrisk skillnad utförs med ^operatören. Samma kan uppnås med metoden 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)

Produktion

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

Prova följande exempel på Python-skal.

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

Andra Python Set-metoder

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 är en ny klass som har en uppsättning egenskaper, men dess element kan inte ändras när de har tilldelats. Medan tuples är oföränderliga listor, är frozensets oföränderliga uppsättningar.

Uppsättningar som kan ändras är otappbara, så de kan inte användas som ordbokstangenter. Å andra sidan är frozensets hashable och kan användas som nycklar till en ordbok.

Frozensets kan skapas med funktionen frozenset ().

Denna datatyp stöder metoder som copy(), difference(), intersection(), isdisjoint(), issubset(), issuperset(), symmetric_difference()och union(). Eftersom den är oföränderlig har den inte metoder som lägger till eller tar bort element.

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

Prova dessa exempel på Python-skal.

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

Intressanta artiklar...