首页 > 解决方案 > 删除重复的项目并在python中添加类似的项目

问题描述

我创建了一个字典,它将接受一个键和两个值,字典将按如下方式工作:

  1. 用户输入了一个项目(项目将是关键)
  2. 用户选择了多少数量(value1)
  3. 价格(价值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)

标签: python

解决方案


您不应该附加到购物车项目。您已经计算了总数,因此只需将购物车项目列表替换为具有新数量和价格的列表即可。

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 行。


推荐阅读