简体   繁体   中英

Removing duplicated items from a list in python

I am working on a restaurant menu project, so far I created my main dishes menu.. but am struggling with one thing, which is the duplication (please run the code below and try it to see what I mean); I want to remove the duplicated item but also i want to add the entered quantity to the corresponding item into the list, for example:

[1.Pesto Pasta, 2.Pizza, 3.Risto]

if the user entered: 1 the first item will be added into a new list called MyOrder, the list MyOrder encapsulate the item, price, and quantity (this needed for the bill) So, then the program will ask the user about the quantity.. assume he/she entered: 2

and then the user added a second item which also 1, and entered the quantity to be 5.. MyOrder list will be as following:

[(1.Pesto Pasta, 2),(1.Pesto Pasta, 5)]

But, what i want is to add 2+5 and remove the duplicated item to be like this

[(1.Pesto Pasta, 7)]

How can i do that? please HELP :(

global items
items = []
global OriginalPrice 
OriginalPrice = []
global numOfItems
numOfItems =[]
global MyOrder
MyOrder = []

def maindish():
dishes = {'1.Pink Sauce Chicken Pasta':2.950,'2.Cheesy Garlic Bread':0.850,'3.Pesto 
Pasta':3.250}
print("\n")
for key,val in dishes.items():
    print(f"{key} - {val}KD")

while True:
    choise = int(input('Enter dish: '))
    quantity = int(input('Enter how many dishes'))
    
    item = list(dishes)[choise-1] #extracting the key
    DishPrice = dishes[item] #extracting value
    
    items.append(item)
    numOfItems.append(quantity)
    OriginalPrice.append(DishPrice)
    a = str(input('N/Y'))
    if(a == 'n'):
        break
    else:
        return maindish()
    

   maindish()
   for i in zip(items,numOfItems):
   MyOrder.append(i)
   print(MyOrder)

You could declare items as a dict before your while True loop:

items = {}

and then replace

items.append(item)
numOfItems.append(quantity)

with

if item in items:
    items[item] += quantity
else:
    items[item] = quantity

Now items will be a dictionary of dish : quantity and you can iterate through it with:

for dish, quantity in items.items():

Although you may want to rename items to something like dish_counts for clarity.

Tuples are definitely a poor choice for data that needs to be continuously updated. My suggestion is to use a dictionary to store the dish names ( key ) with the respective quantities ( value ).

So first off, instead of zipping across items and num_of_items , I'd build a dictionary of item:quantity pairs. Here's a simple example of how I'd implement this.

# replace this:
items.append(item)
numOfItems.append(quantity)

# with this (assuming items as the dict):
if item in items:
    items[item] += quantity
else:
    items[item] = quantity

Similarly I'd make my_order a dictionary with the same logic, thus replacing maindish() definition as follows:

for dish, quantity in items.items():
    if dish in my_order:
        my_order[dish] += quantity
    else:
        my_order[dish] = quantity

Always choose mutable data types when you're performing a lot of updates on your information.

As a side note, I suggest you try to follow PEP8 good practices, at least when it comes to variable names, ie use underscores instead of mixed case to separate words.

You cannot update the items as you are using a tuple which cannot be edited. You can use another list, which can be edited.

I recommend using a dictionary instead of a 2d list.

An even better approach is by using OOP to create Order as an object this also allows you to create multiple orders for multiple people You should also create a generic Food class or use inheritance to make specific foods.

class Food:
    def __init__(self, name, price, quantity):
        self.name =  name
        self.price = price
        self.quantity = quantity

    def increase_quantity(self, quantity):
        self.quantity += quantity
class Order:
    def __init__(self):
        self.order = {}
    
    def add_order(name, price, quantity):
        if name in self.orders:
            self.orders[name].increase_quantity(quantity)
        else:
            self.food1 = Food(name, price, qauntity)
        

In the main code, you can create the as many order as you want

person1 = Order()
person2 = Order()
person1.add_order("pesto pasta" , 2.95, 1)
person1.add_order("pesto pasta" , 2.95, 5)
# now this person has order 6 pesto pastas
person2.add_order("chicken pasta" , 1.5, 2)

You can output the order objects the same way you print dicts and list you can also do with objects by overriding the __str__() method, which returns a string", that is built into all objects in python.

class Food:
# previous code and methods 
    def __str__(self):
        return self.name + str(self.price) + str(self.quantity) 
                + str(self.quantity*self.price)
class Order:
# previous code and methods 
    def __str__(self):
        output = "name | price | quantity | total \n"
        for key, value in self.orders.items():
            output += str(value) + "\n"
        return output

You can change how the output looks as its just string manipulation.

In the main program

person1 = # an order object with all their orders already added
print(person1) #will output result of ```__str__()```:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM