set
I note that when learning is done to facilitate future review, the original tutorial link Python3 Tutorial | Tutorial rookie
Collection (set) is a disorder of not repeated sequence of elements
using braces {}, or set () function creates a set of note: Create an empty set must be set () instead of {}, {} as it is used to create a empty dictionary
created format:
parame = {value1,value2,...}
or
set(value)
fruit = {'apple','banana','orange','pear','banana'}
print(fruit) #集合是无序且不重复的,每次输出的顺序都是随机的
print('orange' in fruit) #判断元素是否在集合内
#集合间的运算
a = set('123456')
b = set('1357984')
print(a-b) #集合a中包含而集合b中不包含的元素
print(a|b) #集合a或b中包含的所有元素
print(a&b) #集合a和b中都包含了的元素
print(a^b) #不同时包含于a和b的元素
Run Results
{ 'PEAR', 'Apple', 'Orange', 'Banana'}
True
{ '. 6', '2'}
{ '. 1', '. 8', '. 4', '. 6', '. 3', '9', '7', '2', '5'}
{ '1', '3', '5', '4'}
{ '6', '9', '7', '2', '8'}
The basic set of operations
Adding elements
s.add(x) 将元素 x 添加到集合 s 中,如果元素已存在,则不进行任何操作
fruit = {'apple','banana','orange','pear','banana'}
print(fruit)
fruit.add('strawberry')
print(fruit)
fruit.add('apple')
print(fruit)
Run Results
{ 'Orange', 'PEAR', 'Apple', 'Banana'}
{ 'Banana', 'Orange', 'Apple', 'Strawberry', 'PEAR'}
{ 'Banana', 'Orange', ' apple ',' strawberry ',' pear '}
s.update(x1,x2,...) #参数可以是列表,元组,字典等
fruit = {'apple','banana','orange','pear','banana'}
print(fruit)
fruit.update(('strawberry',),(1,2,'hello'),[4,5,6])
print(fruit)
Run Results
{ 'Orange', 'Apple', 'Banana', 'PEAR'}
{. 1, 'PEAR', 'Strawberry', 'Banana', 2,. 4,. 5,. 6, 'Apple', 'Orange', 'hello'}
Remove elements
s.remove(x) #将元素 x 从集合 s 中移除,如果元素不存在,则会发生错误
fruit = {'apple','banana','orange','pear','banana'}
print(fruit)
fruit.remove('apple')
print(fruit)
fruit.remove('hello')
print(fruit)
运行结果
{‘apple’, ‘banana’, ‘orange’, ‘pear’}
{‘banana’, ‘orange’, ‘pear’}
Traceback (most recent call last):
File “app.py”, line 5, in <module>
fruit.remove(‘hello’)
KeyError: ‘hello’
s.discard(x) #如果元素不存在,不会发生错误
fruit = {'apple','banana','orange','pear','banana'}
print(fruit)
fruit.remove('apple')
print(fruit)
fruit.remove('hello')
print(fruit)
Results Run
{ 'Banana', 'PEAR', 'Orange', 'Apple'}
{ 'Banana', 'PEAR', 'Orange'}
{ 'Banana', 'PEAR', 'Orange'}
s.pop() #随机删除集合中的一个元素
fruit = {'apple','banana','orange','pear','banana'}
print(fruit)
x = fruit.pop()
print(x)
print(fruit)
Results Run
{ 'Apple', 'PEAR', 'Orange', 'Banana'}
Apple
{ 'PEAR', 'Orange', 'Banana'}
Count the number of set elements
len(s)
fruit = {'apple','banana','orange','pear','banana'}
print(fruit)
print(len(fruit))
Results Run
{ 'Orange', 'Apple', 'Banana', 'PEAR'}
. 4
Empty collection
s.clear()
fruit = {'apple','banana','orange','pear','banana'}
print(fruit)
fruit.clear()
print(fruit)
Results Run
{ 'Orange', 'Banana', 'Apple', 'PEAR'}
SET ()
Determining whether there is an element in the collection
x in s
fruit = {'apple','banana','orange','pear','banana'}
print('apple' in fruit)
print('hello' in fruit)
Operating results
True
False