一、元素分类
有如下值集合 [11,22,33,44,55,66,77,88,99,90...],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中。
即: {'k1': 大于66的所有值, 'k2': 小于66的所有值}
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
l = [11,22,33,44,55,66,77,88,99,90] ls1 = [] ls2 = [] for i in l: if i > 66: ls1.append(i) else: ls2.append(i) print({'k1':ls1,'k2':ls2})
二、查找
查找列表中元素,移除每个元素的空格,并查找以 a或A开头 并且以 c 结尾的所有元素。
li = ["alec", " aric", "Alex", "Tony", "rain"]
tu = ("alec", " aric", "Alex", "Tony", "rain")
dic = {'k1': "alex", 'k2': ' aric', "k3": "Alex", "k4": "Tony"}
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
li = ["alec", " aric", "Alex", "Tony", "rain"] for i in li: l = i.strip() if (l.startswith('a') or l.startswith('A')) and l.endswith('c'): print(l) tu = ("alec", " aric", "Alex", "Tony", "rain") for i in tu: l = i.strip() if (l.startswith('a') or l.startswith('A')) and l.endswith('c'): print(l) dic = {'k1': "alex", 'k2': ' aric',"k3": "Alex", "k4": "Tony"} for key in dic: value1 = dic[key].strip() if (value1.startswith('a') or value1.startswith('A')) and value1.endswith('c'): print(value1)
三、输出商品列表,用户输入序号,显示用户选中的商品
商品 li = ["手机", "电脑", '鼠标垫', '游艇']
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
li = ["手机", "电脑", '鼠标垫', '游艇'] l = [] for i in enumerate(li,1): l.append(i) user_choose = input('请输入你想要购买的商品序号: ') if not user_choose.isdigit():continue print(l[int(user_choose)-1][1])
四、简单购物车
实现打印商品详细信息,用户输入商品和购买个数,则将商品名,价格,购买个数加入购物列表,如果输入为空或其他非法输入,则要求用户重新输入
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
for key in msg_dic: print(key, msg_dic[key]) while True: my_goods = input('请输入你想要购买的商品: ') if my_goods not in msg_dic:continue my_count = input('请输入你想要购买的商品个数: ') if not my_count.isdigit():continue print((my_goods,msg_dic[my_goods],my_count)) break