“Zestawy Pythona” Kod odpowiedzi

Zestaw Python

# A set contains unique elements of which the order is not important
s = set()
s.add(1)
s.add(2)
s.remove(1)
print(s)
# Can also be created from a list (or some other data structures)
num_list = [1,2,3]
set_from_list = set(num_list)
Arno Deceuninck

Zestawy Pythona

# Python also has sets which you can use
# Keep in mind that sets cannot have duplicate of the same value
# This can be useful for removing doubles in a list

mySet = {1, 2, 2, 3, 4, 5, 10, 10, 15}
print(mySet) # {1, 2, 3, 4, 5, 10, 15}

# You can also create a set with 'set([list elements])'

myList = ['apples', 'bananas', 'oranges', 'grapes']
myList.append('apples')
myList.append('oranges')
print(myList) # ['apples', 'bananas', 'oranges', 'grapes', 'apples', 'oranges']

myNewSet = set(myList)
print(myNewSet) # {'apples', 'bananas', 'oranges', 'grapes'}
Ninja Penguin

Zestaw Python

set_name = {item1, item2, ...}
alimehridev

Kiedy używać zestawów Pythona

"""
The Python sets are highly useful to efficiently remove duplicate values from
a collection like a list and to perform common math operations like unions and
intersections.
"""
notPlancha

Odpowiedzi podobne do “Zestawy Pythona”

Pytania podobne do “Zestawy Pythona”

Więcej pokrewnych odpowiedzi na “Zestawy Pythona” w Python

Przeglądaj popularne odpowiedzi na kod według języka

Przeglądaj inne języki kodu