python集合
集合:
list tuple ----> set()
无序不重复的序列,集合
无序----->跟下标相关
s = {1,2,3,4,5} ---->s[1]
for i in s:
print(i)
内置函数:
添加:add update
删除:remove discard pop clear
运算相关函数
- difference()
| union
& intersection()
^ symmetric_difference()
可变和不可变
可变:地址不变里面内容改变 list dict set
不可变:只要内容改变,必须改变地址 int str float tuple frozenset
类型转换:
str ----> list set ... 相互转换
list ---> set tuple dict 相互的转换
函数:
增加代码的复用,减少代码的冗余
def 函数名([参数,]):
函数体
没有参数:
def add():
add()
有参数:
def add(a, b):
result = a+b
print(result)
调用:
add(1,3)
add(2,8)
# 不重复特点:
list1 = [1, 2, 3, 3, 4, 6, 7, 6, 0]
# 声明集合:set
s1 = set()
s2 = {} # 字典:{key:value} 集合{元素1, 元素2, 元素3}
print()
# 应用:
s3 = set(list1)
print(s3)
# 增删改查
# 1.增加 s1 = set()
# add() 添加一个元素
# update 可以添加多个元素
s1.add('hello')
s1.add('小猪佩奇')
print(s1)
t1 = ('林志玲', '言承旭')
s1.update(t1)
print(s1)
# 2.删除 remove 如果存在删除不存在报错KeyError pop clear
s1.remove('言承旭')
print(s1)
# s1.remove('道明寺') # KeyError: '道明寺'
# print(s1)
s1.pop()
print(s1)
s1.clear()
print(s1)
# dicard() 类似remove 在移除不存在的值不会报错
'''
1.产生10个1-20的随机数去除里面的重复项
2.键盘输入一个元素,将此元素从不重复的集合中删除
'''
import random
# 方法1
# list1 = []
# # set1 = set()
# for i in range(10):
# ran = random.randint(1, 20)
# list1.append(ran)
# # set1.update(list1)
# set1 = set(list1)
# print(list1)
# print(set1)
# result = int(input('请输入一个想要删除的数字:'))
# set1.discard(result)
# print(set1)
# 方法2
set1 = set()
for i in range(10):
ran = random.randint(1, 20)
set1.add(ran)
print(set1)
# 其他:符号操作
print(6 in set1)
set2 = {2, 3, 4, 5, 6, 7}
set3 = {2, 3, 4, 5, 6, 7, 8, 9}
print(set2 == set3) # 判断两个集合中的内容是否相等
# 测试:print(set2 != set3)
# (+ * 不支持) - & |
# set4 = set2+set3 报错s
# print(set4)
set4 = set3 - set2 # 差集 difference
set5 = set3.difference(set2)
print(set4, set5)
# &交集 intersection()
set6 = set3 & set2
print(set6)
set7 = set3.intersection(set2)
print(set7)
# | 交集 union() 联合
set9 = set3 | set2
print(set9)
print(set9)
'''
已知两个列表:
l1 = [5, 1, 2, 9, 0, 3]
l2 = [7, 2, 5, 7, 9]
找出两个列表的不同元素
找出两个列表的相同元素
'''
l1 = [5, 1, 2, 9, 0, 3]
l2 = [7, 2, 5, 7, 9]
l1 = set(l1)
l2 = set(l2)
# 对称差集
result = (l1 | l2) - (l1 & l2)
print(result)
result = l1 ^ l2 # 列表中不一样的元素,对称差集, symmetric_difference()
print(result)
'''
difference_update()
l1.difference(l2)
l1.difference_update(l2) update不需要赋值
l1.intersection_update(l2) 交集并赋值
symmetric_difference_update() 对称差集并赋值
update不需要赋值
'''
print(l1.difference_update(l2))
print(l1.intersection_update(l2))
'''
关键字:set
作用:去重
符号:- | & ^
内置函数:
增加:add() update()
删除:remove() discard() pop() clear()
运算:difference() intersection() union() symmetric_difference()
'''
# 可变 和不可变
# 不可变:对象所指向的内存中的值是不可变的
# 不可变的类型:int str float 元组tuple
num = 10
s1 = 'abc'
print(id(s1))
s1 = 'abcd'
print(id(s1))
t1 = (3, 5, 6)
print(id(t1))
t1 = (3, 5)
print(id(t1))
# 可变的元素:该对象所指向的内存中的值是可以改变的
# 可变类型: dict list set
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来源 Wans!
评论
TwikooGitalk