本文是我自己学习过程中整理的一些笔记,来源于[菜鸟笔记],一些学习视频和书籍,不完全正确可能存在错误
集合(set)是一个无序的不重复元素序列,使用{ }表示。
创建集合
创建格式: parame={value1,value2,value3,…} 或者 set(value)
set_name={'zhang','sun','li'}
print(set_name)
*********执行结果************
D:\Python\Python37\python.exe D:/PycharmProjects/pythonProject1/class_4/test.py
{'zhang', 'sun', 'li'}
Process finished with exit code 0
集合是不重复的序列,重复的元素直接去掉,可以使用集合来去重
test = 'abccdfeegg'
a = set(test)
print(a)
**********执行结果***********
D:\Python\Python37\python.exe D:/PycharmProjects/pythonProject1/class_4/test.py
{'g', 'a', 'b', 'e', 'c', 'f', 'd'}
Process finished with exit code 0
添加元素
- 使用.add( )添加元素,不存在则添加,元素已存在不进行操作
set_name={'zhang','sun','li'}
print('添加前:',set_name)
set_name.add('qian')
print('添加不存在的元素后:',set_name)
set_name.add('zhang')
print('添加存在的元素后:',set_name)
********执行结果*********
D:\Python\Python37\python.exe D:/PycharmProjects/pythonProject1/class_4/test.py
添加前: {'zhang', 'li', 'sun'}
添加不存在的元素后: {'qian', 'zhang', 'li', 'sun'}
添加存在的元素后: {'qian', 'zhang', 'li', 'sun'}
Process finished with exit code 0
- 使用.update( ) 添加元素,参数可以是列表,元组,字典等
set_name={'zhang','sun','li'}
print('添加前:',set_name)
set_name.update([1,2,3])
print('添加不存在的元素后:',set_name)
*********执行结果************
D:\Python\Python37\python.exe D:/PycharmProjects/pythonProject1/class_4/test.py
添加前: {'sun', 'li', 'zhang'}
添加不存在的元素后: {1, 2, 3, 'zhang', 'sun', 'li'}
Process finished with exit code 0
删除元素
使用s.remove( )删除元素
set_name={'zhang','sun','li'}
print('删除前:',set_name)
set_name.remove('sun')
print('删除后:',set_name)
***********执行结果**********
D:\Python\Python37\python.exe D:/PycharmProjects/pythonProject1/class_4/test.py
删除前: {'li', 'sun', 'zhang'}
删除后: {'li', 'zhang'}
Process finished with exit code 0
清空集合
使用 s.clear( )清空集合
set_name={'zhang','sun','li'}
clear_set = set_name.clear()
print(clear_set)
***********执行结果*********
D:\Python\Python37\python.exe D:/PycharmProjects/pythonProject1/class_4/test.py
None
Process finished with exit code 0
计算元素个数
使用len( ) 计算元素个数
set_name={'zhang','sun','li'}
print('集合元素个数:',len(set_name))
**********执行结果**********
D:\Python\Python37\python.exe D:/PycharmProjects/pythonProject1/class_4/test.py
集合元素个数: 3
Process finished with exit code 0
判断元素是否存在
使用 in 判断集合中是否存在元素
set_name= set(('zhang','sun','li'))
print(set_name)
print('zhang' in set_name)
print('qian' in set_name)
**********执行结果**********
D:\Python\Python37\python.exe D:/PycharmProjects/pythonProject1/class_4/test.py
{'li', 'sun', 'zhang'}
True
False
Process finished with exit code 0
集合转换成列表
set_name2=set(['zhang','sun','li'])
print('转换前(集合):',set_name2)
set_name2=list(set(['zhang','sun','li']))
print('转换后(列表):',set_name2)
************执行结果************
D:\Python\Python37\python.exe D:/PycharmProjects/pythonProject1/class_4/test.py
转换前(集合): {'zhang', 'sun', 'li'}
转换后(列表): ['zhang', 'sun', 'li']
Process finished with exit code 0
|