集合 set集合特性 1.不同元素組成 集合方法#!/usr/bin/env python3 # -*- coding:utf-8 -*- # 集合方法練習(xí): l1 = [ 2, 3] l2 = [2, 3, 4] # 轉(zhuǎn)換成集合,,相當(dāng)于for循環(huán)取每個(gè)元素加入到集合里 s1 = set(l1) s2 = set(l2) # issubset() 判斷s1是都是s2的子集,是True 不是False print(s1.issubset(s2)) # issuperset() 判斷s2是否是s1的父集,,是True 不是False print(s2.issuperset(s1)) # isdisjoint() 判斷s1和s2是否有交集,,沒有True 有False print(s1.isdisjoint(s2)) # 方法 pop() 隨機(jī)刪除集合中的元素 s1.pop() s2.pop() print("pop方法:", s1, s2, sep="\n") # 方法remove() 刪除集合中指定的元素,不存在報(bào)錯(cuò) # s1.remove(1) # s2.remove(3) # print("remove方法:", s1, s2, sep="\n") # 方法discard()刪除集合中指定的元素,不存在不報(bào)錯(cuò) s1.discard(99) s2.discard(99) # 方法 add(),向集合中增加元素 s1.add(5) s2.add(6) print("add方法:", s1, s2, sep="\n") # update,將一個(gè)iterable對(duì)象添加到s1中 s1.update("山河萬里") s1.update([33, 44, 55]) s1.update((11, 22, 33,)) # 把字典添加到集合的時(shí)候,默認(rèn)添加鍵,,指定items()則將鍵值對(duì)轉(zhuǎn)換成元祖添加 s1.update({"k1": "縱", "k2": "情"}.items()) print(s1) # 集合并集 print("集合并集".center(30, "*")) print(s1 | s2) print(s1.union(s2)) # 集合交集 print("集合交集".center(30, "*")) print(s1 & s2) print(s1.intersection(s2)) # s1跟s2的差集 print("s1跟s2的差集".center(30, "*")) print(s1 - s2) print(s1.difference(s2)) # s2跟s1的差集 print("s2跟s1的差集".center(30, "*")) print(s2 - s1) print(s2.difference(s1)) # s1|s2的交叉補(bǔ)集 print("s1|s2的交叉補(bǔ)集".center(30, "*")) print(s2 ^ s1) print(s2.symmetric_difference(s1)) # s1|s2的差集,,并賦值給s1 print("s1|s2的差集,并賦值給s1".center(30, "*")) s1.difference_update(s2) print(s1, s2) # s2|s1的差集,,并賦值給s2 print("s2|s1的差集,,并賦值給s2".center(30, "*")) s2.difference_update(s1) print(s2, s1) # s1|s2的交集,,并賦值給s1 print("s1|s2的交集,并賦值給s1".center(30, "*")) s1.intersection_update(s2) print(s1, s2) # s1|s2的交叉補(bǔ)集,,并賦值給s1 print("s1|s2的交叉補(bǔ)集,,并賦值給s1".center(30, "*")) s1.symmetric_difference_update(s2) print(s1, s2) # 定義不可變集合 函數(shù)定義函數(shù)函數(shù)式編程最重要的是增強(qiáng)代碼的重用性和可讀性 def 函數(shù)名(param): 函數(shù)的定義要點(diǎn):
返回值函數(shù)是一個(gè)功能塊,,該功能到底執(zhí)行成功與否,需要通過返回值來告知調(diào)用者,。參數(shù)# 參數(shù)有:形參,,實(shí)參,位置參數(shù)(必須一一對(duì)應(yīng)),,關(guān)鍵字參數(shù)(位置不需要固定) # 默認(rèn)參數(shù) # def handle(x, type="mysql"): # print(x) # print(type) # 參數(shù)組 # def test(x, *args): # print(x) # print(args) # # test(1, 2, 3, 4, 5, 6) # def test(x, **kwargs): # print(x) # print(kwargs) # def test(x, *args, **kwargs): # print(x) # print(kwargs)來源:https://www./content-1-617901.html |
|