用Python实现给定列表如下: [ ['华为Mate30 Pro',5800],['IPhone11',5500], ['小米MIX Alpha',19999],[ 小米9 Pro ',3700],['vivo NEX3',5700], ['三星W 2019至尊版',18999] ],实现一个购物车,在未退出购物车前可一直通过输入商品编号添加入购物车列表内,当用户输入’q’时退出购物车并打印购物清单,且统计数量和价格。
时间: 2024-01-20 09:02:34 浏览: 208
华为Mate20Pro手机原厂维修图纸 原理图 电路图 故障维修图(PDF版).zip
5星 · 资源好评率100%
好的,以下是Python实现的代码:
```python
items = [['华为Mate30 Pro',5800],['IPhone11',5500],['小米MIX Alpha',19999],['小米9 Pro',3700],['vivo NEX3',5700],['三星W 2019至尊版',18999]]
cart = []
total_price = 0
total_num = 0
while True:
print("商品列表")
for i in range(len(items)):
print(str(i) + "." + items[i][0] + " " + str(items[i][1]))
order = input("please input your numbers:")
if order == "q":
break
elif int(order) >= len(items):
print("无效的商品编号,请重新选择")
else:
cart.append(items[int(order)])
total_price += items[int(order)][1]
total_num += 1
print("您以购买如下商品:")
for i in range(len(cart)):
print(str(i) + "." + cart[i][0] + " " + str(cart[i][1]))
print("总数量: " + str(total_num))
print("总价格: " + str(total_price))
```
运行结果为:
```
商品列表
0.华为Mate30 Pro 5800
1.IPhone11 5500
2.小米MIX Alpha 19999
3.小米9 Pro 3700
4.vivo NEX3 5700
5.三星W 2019至尊版 18999
please input your numbers:2
商品列表
0.华为Mate30 Pro 5800
1.IPhone11 5500
2.小米MIX Alpha 19999
3.小米9 Pro 3700
4.vivo NEX3 5700
5.三星W 2019至尊版 18999
please input your numbers:3
商品列表
0.华为Mate30 Pro 5800
1.IPhone11 5500
2.小米MIX Alpha 19999
3.小米9 Pro 3700
4.vivo NEX3 5700
5.三星W 2019至尊版 18999
please input your numbers:q
您以购买如下商品:
0.小米MIX Alpha 19999
1.小米9 Pro 3700
总数量: 2
总价格: 23699
```
阅读全文