Python小白学习笔记四(容器类型 6 总结与综合练习 )
总结与综合练习 - 容器
字符串:存储字符编码,不可变序列
列表:存储变量,可变序列
元组:存储变量,不可变序列
字典:存储键值对,可变散列
集合:存储键,可变散列
可变:预留空间,自动扩容 --> 动态改变
不可变:按需分配 --> 节省内存
序列: 有顺序(索引/切片)
练习1:排序算法:
1 # 自定义排序算法 2 list = [51,24,5,15,22,4,9,18,74] 3 # 取数据: 前几个数据(不包括最后不一个) 4 for a in range(len(list)-1): 5 # 作比较:用取出的数据与后面的数据进行比较 6 for b in range(a+1,len(list)): 7 if list[a] < list[b]: 8 list[a],list[b] = list[b],list[a] 9 print(list)
练习2:容器的综合练习:
1 # 商品字典 2 dict_commodity_infos = { 3 1001: {"name": "屠龙刀", "price": 10000}, 4 1002: {"name": "倚天剑", "price": 10000}, 5 1003: {"name": "金箍棒", "price": 52100}, 6 1004: {"name": "口罩", "price": 20}, 7 1005: {"name": "酒精", "price": 30}, 8 } 9 # 订单列表 10 list_orders = [ 11 {"cid": 1001, "count": 1}, 12 {"cid": 1002, "count": 3}, 13 {"cid": 1005, "count": 2}, 14 ] 15 # 1.打印所有商品信息, 16 # 格式:商品编号xx,商品名称xx,商品单价xx. 17 # 2. 打印所有订单中的信息, 18 # 格式:商品编号xx,购买数量xx. 19 # 3. 打印所有订单中的商品信息, 20 # 格式:商品名称xx,商品单价:xx,数量xx. 21 # 4. 查找数量最多的订单(使用自定义算法,不使用内置函数) 22 # 5. 根据购买数量对订单列表降序(大->小)排列 23 #1 24 for cid,info in dict_commodity_infos.items(): 25 print("商品单号%d,商品名称%s,商品价格%d" % (cid,info['name'],info['price']) ) 26 #2 27 for order in list_orders: 28 print("商品单号%d,购买数量%d" % (order['cid'],order['count'])) 29 30 #3 31 for order in list_orders: 32 cid = order['cid'] 33 commodity = dict_commodity_infos[cid] 34 print("商品名称%s,商品价格%d,数量%d" % (commodity['name'],commodity['price'],order['count'])) 35 36 # 4. 查找数量最多的订单(使用自定义算法,不使用内置函数) 37 max_value = list_orders[0] 38 for i in range(1, len(list_orders)): 39 if max_value["count"] < list_orders[i]["count"]: 40 max_value = list_orders[i] 41 print(max_value) 42 43 # 5. 根据购买数量对订单列表降序(大->小)排列 44 for r in range(len(list_orders) - 1): 45 for c in range(r + 1, len(list_orders)): 46 if list_orders[r]["count"] < list_orders[c]["count"]: 47 list_orders[r], list_orders[c] = list_orders[c], list_orders[r] 48 print(list_orders)
浙公网安备 33010602011771号