RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:8:30-17:00
你可能遇到了下面的问题
关闭右侧工具栏

新闻中心

这里有您想知道的互联网营销解决方案
python集合和三大生成方式
#集合是无序的 元素不能重复  集合是可变的  集合允许进行数学运算
college1 = {"a","b","e"}
print(college1)

college2 = set(["a","b","c","d"])
print(college2)

#使用set创建字符串集合
college3 = set("中华人民共和国")
print(college3)#可以得到每个汉字的字符串

#集合的数学运算  交集 并集
college_in = college1.intersection(college2)
print(college_in)  #获得一个新的交集
college1.intersection_update(college2)
print(college1)  #将新的交集覆盖之前的内容

#并集去重
c4=college1.union(college2)
print(c4)

#差集  两个集合之间差异的而部分
c5 = college1.difference(college2)#具有返回值
print(c5)

#集合间的关系操作
s1 = {1,2,4,5,6}
s2 = {6,5,4,2,1}
print(s1 == s2)

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

print(s4.issuperset(s3))#判断是否为父级
s4.isdisjoint(s3)#是否重复的元素

#集合增加删除修改操作
for c in college2:
    print(c,end="")
print("")
print("a" in college2) #判断元素是否在集合内

#新增元素
college2.add("f")
print(college2)

s=['f','m','p']
college2.update(s)#没有返回值
print(college2)

college2.remove('b')#删除不存在元素时会报错
college2.discard('b')#不存在时会直接跳过
print(college2)

#三种内置生成式  [被追加语句  循环  判断]|{}
#列表生产式
lst = [i * 10 for i in range(10,20) if i%2 == 0]
print(lst)
#字典生成
lst = ["张山","李四",'王五']
dict1 = {i+1:lst[i] for i in range(0,len(lst)) }
print(dict1)
#集合生成
set1 ={i*j for i in range(1,4) for j in range(1,4) if i == j}
print(set1)

文章题目:python集合和三大生成方式
网站链接:http://sczitong.cn/article/jjgdcp.html