python入门_老男孩_集合_元祖
集合 可变数据类型,内置元素必须是不可变类型,无序,不重复
增
set.add
set.update
删
del
pop
remove
clear
查
for
切片
# 集合 # 创建 set1 = set({1,2,3}) # 集合内置元素必须是不可变类型 # set2 = set({1,[2,3],{'name':larry}}) false # 增 set1.add('小赵女神') print(set1) set1.update('love') print(set1) # 删 set1.pop() # 随机删除 print(set1.pop()) # 有返回值 print(set1) set1.remove('l') # 按元素删除 print(set1) set1.clear() # 清空集合 print(set1) # 返回set() # del set1 # 删除集合 # print(set1) # 查 set1 = set({1,2,3}) for i in set1: print(i,type(i)) # print(set1[0]) # 不支持索引 # print(set1[0:3] # 不支持切片
运算
intersection
union
difference
issubset
issuperset
# 运算操作 # 交集 set2 = {1,2,3,4,5} set3= {3,4,5,6,7,8} set4 = set2 & set3 set5 = set2.intersection(set3) print(set4, set5) # 并集 set6 = set2 | set3 set7 = set2.union(set3) print(set6, set7) # 差集 set8 = set2 - set3 set9 = set2.difference(set3) print(set8, set9) # 子集 set3 = {1,2,3} set4 = {1,2,3,4,5,6} print(set3 < set4) print(set3.issubset(set4)) print(set4 > set3)
去重小案例
# 列表去重的两种方法 # 方法一,转换成集合 li = [1,3,3,44,5,33,44] temp = set(li) li = list(temp) print(li) # 方法二,for循环 li = ['a', 'b', 'c', 'a'] l = [] for i in li: for i not in l: l.append(i) print(l)
元祖
创建
>>>tup1 = ('Google', 'Runoob', 1997, 2000); >>> tup2 = (1, 2, 3, 4, 5 ); >>> tup3 = "a", "b", "c", "d"; # 不需要括号也可以 >>> type(tup3) <class 'tuple'>
类型
>>>tup1 = (50) >>> type(tup1) # 不加逗号,类型为整型 <class 'int'> >>> tup1 = (50,) >>> type(tup1) # 加上逗号,类型为元组 <class 'tuple'>
查
tup1 = ('Google', 'Runoob', 1997, 2000) tup2 = (1, 2, 3, 4, 5, 6, 7 ) print ("tup1[0]: ", tup1[0]) print ("tup2[1:5]: ", tup2[1:5])
拼接
tup1 = (12, 34.56); tup2 = ('abc', 'xyz') # 以下修改元组元素操作是非法的。 # tup1[0] = 100 # 创建一个新的元组 tup3 = tup1 + tup2; print (tup3)