【列表中的重复数据,使用for循环遍历列表时,最后只取一次。】
1 #商店里的商品列表 2 com = [ 3 ("iphone",5800), 4 ("macbook",9000), 5 ("coffee",320), 6 ("pythonbook",80), 7 ("bicyle",1500) 8 ] 9 shoplist = []#购物车变量 10 11 salary = input("请输入您的预算:")#总共有5000改为可以选多少钱 12 if salary.isdigit():#验证 13 salary = int(salary) 14 yue = salary 15 16 while yue >= 0: #形成一个无限循环 17 18 for i, v in enumerate(com, 1): # 打印商品内容 19 print(i, '>', v) 20 comd_num = input("输入商品编号(1...5)或退出(q):") #引导选择商品 21 22 if comd_num.isdigit(): #验证输入是否合法 23 comd_num = int(comd_num) 24 if comd_num > 0 and comd_num <= len(com): 25 p_com = com[comd_num-1] #将选择的商品选出来 26 if p_com[1] < yue: 27 yue -= p_com[1] # 买了要扣预算 28 shoplist.append(p_com) 29 print("购物车商品有:", shoplist) 30 print("余额还有:", yue) 31 else: 32 print("购物车商品有:", shoplist) # 用户选商品编号,调用商品价格进行判断钱够不够 33 print("您的余额不足!还有%s"%yue) 34 else: 35 print("无此商品") 36 elif comd_num == "q": 37 print("-------------您已购买如下商品--------------") 38 for i in shoplist: 39 if shoplist.count(i) >= 2: 40 print(i,"*",shoplist.count(i)) 41 else: 42 print(i) 43 print("--------------欢迎下次光临!---------------") 44 break 45 else: 46 print("非法字符")
余额 = 200 买了2本书,退出后的结果是
输入商品编号(1...5)或退出(q):q
-------------您已购买如下商品--------------
('pythonbook', 80) * 2
('pythonbook', 80) * 2
--------------欢迎下次光临!---------------
怎么处理才能变成
-------------您已购买如下商品--------------
('pythonbook', 80) * 2
--------------欢迎下次光临!---------------
# __author__:"watalo" # date: 2019/9/8 # 商店里的商品列表 com = { 1: ["iphone", 5800], 2: ["macbook", 9000], 3: ["coffee", 320], 4: ["pythonbook", 80], 5: ["bicyle", 1500] } shoplist = [] # 购物车变量 salary = input("请输入您的预算:") # 总共有5000改为可以选多少钱 if salary.isdigit(): # 验证 salary = int(salary) yue = salary while yue >= 0: # 形成一个无限循环 for i in com.keys(): # 打印商品内容 print(i, '>>>','商品名称:',com[i][0],'单价:',com[i][1],'元/件') comd_num = input("输入商品编号(1...5)或退出(q):") # 引导选择商品 if comd_num.isdigit(): # 验证输入是否合法 comd_num = int(comd_num) if comd_num > 0 and comd_num <= len(com): p_com = list(com.values())[comd_num - 1] # 将选择的商品选出来 if p_com[1] < yue: yue -= p_com[1] # 买了要扣预算 shoplist.append(p_com) print("购物车商品有:", shoplist) print("余额还有:", yue) else: print("购物车商品有:", shoplist) # 用户选商品编号,调用商品价格进行判断钱够不够 print("您的余额不足!还有%s" % yue) else: print("无此商品") elif comd_num == "q": list1 = [] #过渡列表,装已选商品名称 for v in shoplist: list1.append(v[0]) # 遍历已选商品,v是一个["bicyle", 1500],不能用到集合里,所以要 list2 = list(set(list1)) # 用集合去重 print("-------------您已购买如下商品--------------") for i in list2: if list1.count(i) >= 2: print(i, "*", list1.count(i)) else: print(i,'*1') print("--------------欢迎下次光临!---------------") break else: print("非法字符")
经过休假插空学习,终于实现了这个目标,哈哈哈