Python集合操作

# 集合的创建
college1 = {"哲学", "经济学", "法学" , "教育学" }
print(college1)

#set()内置函数从其他数据结构转换
college2 = set(["金融学","哲学"])
print(college2)
#使用set创建字符串集合
college3 = set("中华人民共和国")
print(college3)
#空集合的创建
college4 = {}
college4 = set()
print(type(college4))
# 集合的数学运算
college1 = {"哲学", "经济学", "法学" , "教育学" }
college2 = set(["金融学","哲学", "经济学", "法学"])
#交集,获取两个集合中重复的部分,新建一个集合
c3 = college1.intersection(college2)
print(c3)
#更新原有集合
college1 .intersection_update(college2)
print(college1)

#并集,将所有的集合所以元素合并,去重
college1 = {"哲学", "经济学", "法学" , "教育学" }
college2 = set(["金融学","哲学", "经济学", "法学"])
c4 = college1.union(college2)
print(c4)

#差集,是指两个集合之间差异的部分
c5 = college1.difference(college2)
print(c5)
# symmetric_difference代表双向差集
c6 = college1.symmetric_difference(college2)
print(c6)
college1.difference_update(college2)
print(college1)
#集合间的关系操作
s1 = {1,2,3,4,5,6}
s2 = {6,5,4,3,2,1}
# ==
print(s1 == s2)

s3 = {4,5,6,7}
s4 = {1,2,3,4,5,6,7,8}
# issubset判断是否为子集
print(s3.issubset(s4))
# issuperset判断是否为父集
print(s4.issuperset(s3))

s5 = {5}
s6 = {1,2,3,4,5,6}
#isdisjoint函数判断两个集合是否存在重复元素
#True代表不存在重复元素,False则代表存在重复
print(s5.isdisjoint(s6))
#集合的遍历
college1 = {"哲学" , "经济学" , "法学" , "教育学"}
for c in college1:
    print(c)

#判断元素存在
print("哲学" in college1)
print("计算机学" in college1)
#集合不支持按索引提取数据
#print(college[3])
#新增数据,一次只能添加一个元素
college1.add("计算机学")
college1.add("法学")
print(college1)

#update方法来一次添加多个元素
college1.update(( "工程学"))
print(college1)
#更新操作是要删除原有元素,再创建新元素
#remove中如果删除不存在的元素时,会报错
#college1.remove("生物学")
#discard删除元素如果不存在,则会忽略
college1.discard("生物")
college1.add("医学")
print(college1)
#生成式
#列表生成式
lst1 = []
for i in range(10,20):
    lst1.append(i * 10)
print(lst1)

lst2 = [i * 10 for i in range(10,20)]
print(lst2)

lst3 = [i * 10 for i in range(10,20) if i % 2 == 0]
print(lst3)

for i in range(10,20):
    if i %2 == 0:
        lst3.append(i * 10)
print(lst3)

lst4 = [i * j for i in range(1,5) for j in range(1,5)]
print(lst4)
for i in range(1,5):
    for j in range(1,5):
        lst4.append(i * j)
#字典生成式
lst5 = ['张三' , '李四' , '王五']
dict1 = {i+1:lst5[i] for i in range(0,len(lst5))}
print(dict1)
for i in range(0,len(lst5)):
    dict1[i+1] = lst5[i]
#集合生成式
set1 = { i * j for i in range(1,4) for j in range(1,4) if i == j}
print(set1)

for i in range(1,4):
    for j in range(1,4):
        if i == j:
            set1.add(i * j)
print(set1)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值