代码如下,没有借鉴其他代码,可能过于复杂:
products = [["iphone", 6888], ["MacPro", 14800], ["小米6", 2499], ["Coffee", 31], ["Book", 60], ["Nike", 699]]
print("-" * 5 + " 商品列表 " + "-" * 5)
for i in range(6): # 输出商品列表
print(i, end="\t")
print(products[i][0], end="\t")
print(products[i][1], end="\t")
print()
Trolley = [] # 购物车,该列表用于储存列表,即以列表为元素
Shopping = [] # 商品,用于存储顾客现在想购买的商品信息,只存储一个商品的信息,随后置空
ShoppingNum = input("请输入您想购买的商品编号:")
while ShoppingNum != "q":
v = [x[0] for x in Trolley] # 取Trolley列表的第一列元素
if ShoppingNum in v: # 如果有重复商品,将商品数量加一即可
n = v.index(ShoppingNum)
Trolley[n][3] += 1
else: # 没有重复商品,将商品信息存入Shopping,再将Shopping存入Trolley,随后将Shopping置空
Shopping.append(ShoppingNum)
Shopping.append(products[int(ShoppingNum)][0])
Shopping.append(products[int(ShoppingNum)][1])
Shopping.append(1) # 新商品数量置为1
Trolley.append(Shopping)
Shopping = []
ShoppingNum = input("请输入您想购买的商品编号:")
print("-" * 5 + " 购物车 " + "-" * 5)
for i in range(len(Trolley)):
print(Trolley[i][0], end="\t")
print(Trolley[i][1], end="\t")
print(Trolley[i][2], " ", end="\t") # 格式化输出购物车列表,由于商品编码为1的商品价格超过4位数少于8位数,故在价格后加空格
print("*", Trolley[i][3], end="\t\t")
print()
?运行效果如下:
|