Aktualizacja zestawu Pythona ()

Metoda set update () w Pythonie aktualizuje zestaw, dodając elementy z innych elementów iteracyjnych.

Składnia update()to:

 A.update(iterable)

Tutaj A jest zbiorem, a iterowalność może być dowolną iterowalną, taką jak lista, zestaw, słownik, łańcuch itp. Elementy iterowalne są dodawane do zestawu A.

Weźmy inny przykład:

 A.update(iter1, iter2, iter3)

Tutaj elementy iterable iter1, iter2 i iter3 są dodawane do zestawu A.

Wartość zwracana z update ()

Ta update()metoda set zwraca None(nic nie zwraca).

Przykład 1: Python set update ()

 A = ('a', 'b') B = (1, 2, 3) result = A.update(B) print('A =', A) print('result =', result)

Wynik

 A = ('a', 1, 2, 3, 'b') wynik = brak

Przykład 2: Dodaj elementy łańcucha i słownika do zestawu

 string_alphabet = 'abc' numbers_set = (1, 2) # add elements of the string to the set numbers_set.update(string_alphabet) print('numbers_set =', numbers_set) info_dictionary = ('key': 1, 'lock' : 2) numbers_set = ('a', 'b') # add keys of dictionary to the set numbers_set.update(info_dictionary) print('numbers_set =', numbers_set)

Wynik

 zestaw_liczb = ('c', 1, 2, 'b', 'a') zestaw_liczb = ('klucz', 'b', 'zamek', 'a')

Uwaga: Jeśli do update()metody przekazywane są słowniki , klucze słowników są dodawane do zestawu.

Interesujące artykuły...