一、字典推导式
1 """ 2 字典推导式 3 练习:exercise01.py 4 练习:exercise02.py 5 """ 6 # 1 2 3 4 ... 10 -> 平方 7 dict01 = {} 8 for item in range(1, 11): 9 dict01[item] = item ** 2 10 print(dict01) 11 # 推导式: 12 dict02 = {item: item ** 2 13 for item in range(1, 11)} 14 print(dict02) 15 16 # 只记录大于5的数字 17 dict01 = {} 18 for item in range(1, 11): 19 if item >5: 20 dict01[item] = item ** 2 21 22 print(dict01) 23 24 dict02 = {item: item ** 2 25 for item in range(1, 11) if item >5} 26 print(dict02)
二、集合
1 """ 2 集合set 3 练习:exercise03 4 练习:exercise04 5 """ 6 # 1. 创建集合 7 set01 = set() 8 # set --> str 9 set01 = set("abcac") 10 list01 = list(set01) 11 str01 = "".join(list01) 12 print(str01) # "bca" 13 # 创建具有默认值的集合 14 set02 = {"a", "b", "a"} 15 16 # 2. 添加元素 17 set02.add("qtx") 18 19 # 3. 删除元素 20 set02.remove("a") 21 22 # 4. 获取所有元素 23 for item in set02: 24 print(item) 25 26 # 5. 数学运算 27 set01 = {1, 2, 3} 28 set02 = {2, 3, 4} 29 # 交集 30 print(set01 & set02) # {2,3} 31 # 并集 32 print(set01 | set02) # {1, 2, 3, 4} 33 # 补集 34 print(set01 ^ set02) # {1, 4} 35 print(set01 - set02) # {1} 36 print(set02 - set01) # {4} 37 38 # 子集 39 set03 = {1, 2} 40 print(set03 < set01) 41 # 超集 42 print(set01 > set03)
三、固定集合
1 """ 2 固定集合 3 """ 4 set01 = frozenset([1, 2, 3, 3, 5]) 5 list02 = list(set01) 6 print(set01) 7 print(list02)
四、列表推导式嵌套
1 """ 2 列表推导式嵌套 3 练习:exercise09.py 4 16:55 5 """ 6 list01 = ["a", "b", "c"] 7 list02 = ["A", "B", "C"] 8 list03 = [] 9 for r in list01: 10 for c in list02: 11 list03.append(r + c) 12 13 print(list03) 14 15 list04 = [r + c for r in list01 for c in list02] 16 print(list04) 17 18 # 练习:列表的全排列 19 # [“香蕉”,"苹果","哈密瓜"] 20 # [“可乐”,"牛奶"] 21 list01 = ["香蕉","苹果","哈密瓜"] 22 list02 = ["可乐","牛奶"] 23 list03 = [] 24 for r in list01: 25 for c in list02: 26 list03.append(r+c) 27 list04 = [r+c for r in list01 for c in list02] 28 print(list03) 29 print(list03)
字典内嵌列表内存图
五、自定义函数
1 """ 2 自定义函数 3 练习:exercise10.py 4 练习:exercise11.py 5 """ 6 7 """ 8 print("直拳") 9 print("摆拳") 10 print("肘击") 11 print("临门一脚") 12 #............... 13 print("直拳") 14 print("摆拳") 15 print("肘击") 16 print("临门一脚") 17 #............... 18 print("直拳") 19 print("摆拳") 20 print("肘击") 21 print("临门一脚") 22 """ 23 24 25 # 定义(做功能)函数 26 def attack(): 27 """ 28 单次攻击 29 """ 30 print("临门一脚") 31 print("直拳") 32 print("摆拳") 33 print("肘击") 34 35 36 # 形式参数 37 def attack_repeat(count): 38 """ 39 重复攻击 40 :param count: 攻击次数,int类型 41 """ 42 for i in range(count): 43 print("临门一脚") 44 print("直拳") 45 print("摆拳") 46 print("肘击") 47 48 49 # 调用函数 50 attack() 51 # ............... 52 # 调用函数 53 attack() 54 # ............... 55 # 调用函数 56 attack() 57 print("--------------") 58 # 调用函数 59 # 实际参数 60 attack_repeat(2)
方阵置换算法图