python - 删除重复的项目并在python中添加类似的项目
问题描述
我创建了一个字典,它将接受一个键和两个值,字典将按如下方式工作:
- 用户输入了一个项目(项目将是关键)
- 用户选择了多少数量(value1)
- 价格(价值2)
我试图接近的是我想将所有数量加在一起,这意味着如果用户选择了具有不同数量的相同项目(例如,用户在第一次迭代和数量中选择了 pin 意大利面,在第二次迭代中用户再次选择了粉色意大利面和数量3),由于它是同一个项目,我必须添加第一次迭代数量“2”和第二次迭代数量“3”总共为 5。字典内容将是 {'item':[5,3.5]}
在我的代码中,我将获得 n 个具有 2 个值的键,字典定义为 global..
这是我的代码的输出:
{'Pink Pasta ': [2, 3.5, 5, 3.5], 'Mushroum Risto ': [3, 5.75, 7, 5.75]}
first iteration user chose pink pasta, quantity = 2
Second iteration user again chose pink pasta, quantity = 3
Third iteration user chose mushroom Risotto, quantity = 3
Fourth iteration again user chose mushroom Risotto, quantity = 4
这就是我想要的:
{'Pink Pasta ': [5, 3.5], 'Mushroum Risto ': [7, 5.75]}
这是我的代码的一部分,
choise = int(input('Enter dish number: '))
quantity = int(input('Enter how many dishes: '))
item = list(MyDictonary)[choise-1] #extracting the key
DishPrice = float(MyDictonary[item]) #extracting value
if item in Items: #checking if the item is already selected
Items[item] += quantity #if yes, update the new quantity +
previous quantity
else:
Items[item] = quantity
toCart.setdefault(item,[])
if item in Items:
toCart[item].append(Items[item])
toCart[item].append(DishPrice)
print(toCart)
解决方案
您不应该附加到购物车项目。您已经计算了总数,因此只需将购物车项目列表替换为具有新数量和价格的列表即可。
choise = int(input('Enter dish number: '))
quantity = int(input('Enter how many dishes: '))
item = list(MyDictonary)[choise-1] #extracting the key
DishPrice = float(MyDictonary[item]) #extracting value
if item in Items: #checking if the item is already selected
Items[item] += quantity #if yes, update the new quantity + previous quantity
else:
Items[item] = quantity
toCart[item] = [Items[item], DishPrice]
print(toCart)
也不需要第二个if item in Items:
,因为您之前刚刚创建了 2 行。
推荐阅读
- html - Bootstrap 4''面具''中的CSS
- mysql - 如何明智地检查付款月份
- docker - 如何使用 Docker 和 Circleci 将映像部署到 EC2。光盘
- java - 如何更改字体、文本大小和设置文本位置中心 ToolBar Android?
- laravel - 如何使用 laravel 8 插入两个表?这是我的代码
- swift - JSON 数组到 Swift 数组
- gitlab - Gitlab CI:为 CI 和合并请求构建,但仅将 CI 发布到页面
- c - 在 C 中与循环 sigwait 并行测量时间
- c++ - 为什么以及何时我们可以在 C++ 中省略 std 关键字?
- apache-nifi - NiFi:修改 JSON 的 ReplaceText 替代方案