| Hosted by CoCalc | Download
Kernel: Python 3 (Anaconda)
a = set() print(a) a = set('hello') print(a) a = {'a', 'b', 'c', 'd'} print(a) a = {i ** 2 for i in range(10)} # генератор множеств print(a) print(type(a))
set() {'o', 'h', 'e', 'l'} {'c', 'd', 'b', 'a'} {0, 1, 64, 4, 36, 9, 16, 49, 81, 25} <class 'set'>
a = {} # А так нельзя! type(a)
dict
words = ['hello', 'daddy', 'hello', 'mum'] s = set(words) print(s)
{'daddy', 'mum', 'hello'}
len(s) # длина множества
3
'mum' in s # принадлежит ли 'mum' множеству s
True
1 in s # принадлежит ли 1 множеству s.
False
set1 = {i*2+1 for i in range(10)} # генератор множеств set2 = {i*2 for i in range(10)} # генератор множеств print(set1) print(set2)
{1, 3, 5, 7, 9, 11, 13, 15, 17, 19} {0, 2, 4, 6, 8, 10, 12, 14, 16, 18}

set.isdisjoint(other) - истина, если set и other не имеют общих элементов.

set1.isdisjoint(set2)
True
set3 = set1 set1 == set3 # все элементы set принадлежат other, все элементы other принадлежат set.
True

set.union(other, ...) или set | other | ... - объединение нескольких множеств.

set1.union(set2,set3)
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19}

set.intersection(other, ...) или set & other & ... - пересечение

set1.intersection(set2,set3)
set()