Home > front end >  How to not add duplicate list values but instead add a counter to count each item?
How to not add duplicate list values but instead add a counter to count each item?

Time:05-05

elif int(groceriesInput) in range(len(groceries) 1):
    optionSelect = input("\nAdd "   (groceries[int(groceriesInput)- 1][0])   " to the cart? (y or n): ")
    if optionSelect == "y" or optionSelect == "Y":
        if groceries[int(groceriesInput)-1] in cart:
            os.system('cls')
        else:
            os.system('cls')
            cart.append(groceries[int(groceriesInput)- 1])

How would I add a counter before each item without adding a duplicate item to the list?

My function builds the list from reading a file.

For example this is the output I want:

2 milk

instead of:

milk milk

[['eggs', 1.99], ['milk', 3.59], ['salmon', 9.99], ['bread', 3.25], ['bean dip', 2.99], ['Fat Tire Ale', 8.99], ['Greek yogurt', 4.99], ['brocoli', 2.29], ['tomatos', 3.19], ['apples', 5.99], ['chicken', 10.99], ['chips', 3.69], ['muesli', 4.99], ['Nine Lives catfood', 6.39], ['goat cheese', 5.19], ['parmesan cheese', 5.99], ['Pinot Noir', 18.5]] this is the list

CodePudding user response:

So, for each entry in your list, you split it into two words: name and price. Since, we are only concerned with the item name, we store the value inside entry[0] into item, which is basically the name of some item. Now, we assume that this is the first time we are encountering this item, so we set isFirst equal to True.

Now, we go through each item stored in your output list: out. Since, each item inside out looks like: COUNT NAME, we split it, and check if current item's name is found inside this splitted string. If it does, we retrieve the value of its count and add one to it.

We now get the index of this item, set the incremented value of count to it, set the isFirst flag to False, since we are not encountering this item for the first time, and break out of the loop.

If isFirst was set to True, i.e., it was out first time encountering such item, we simply append 1 ITEM_NAME to the output list.

out = []

for entry in originalList:
    item = entry[0]
    isFirst = True
    for s in out:
        if item in s.split():
            count = int(s.split()[0])   1
            index = out.index(s)
            out[index] = f"{count} {item}"
            isFirst = False
            break
    if isFirst:
        out.append(f"1 {item}")

Some other improvements to your code:

Try to use f-strings to represent formatted strings (those where you need a variable's value inside). So, the line where you are asking for user's input, you can replace it with:

optionSelect = input(f"\nAdd {groceries[int(groceriesInput)- 1][0]} to the cart? (y or n):")
  • Related