简体   繁体   中英

seraching every element of a list for only one time

i want to create a summary of ingredients, but i dont know how do ignore elments, i've already counted...

tried to delete visited elements, but it ends with index errors

source looks like:

<br>
1.[(Ing1,350grams),(Ing4,200grams)]<br>
2.[(Ing2,2000grams),(Ing1,250grams),(Ing7,50grams),(Ing5,100grams)]<br>
3.[(Ing1,100grams),(Ing7,120grams)]<br>
4.[(Ing3,80grams),(Ing5,70grams),(Ing1,90grams)]<br>
...

These should result in:

<br>
Ing1:790grams<br>
Ing2:2000grams<br>
Ing3:80grams<br>
Ing4:200grams<br>
Ing5:170grams<br>
Ing7:170grams<br>

I tried these code: (eating is an list of ing objects, getName() is the name as string, add() is a function to add the values of the ings)

    # eating is my list of ing objects
    new_eating = []
    for i in range(0,len(eating)):
        for j in range(i,len(eating)):
            if (i != j) and (eating[i].getName() == eating[j].getName()):
                eating[i] = eating[i].add(eating[j])
        new_eating.append(eating[i])

But this doesn't work...

I would suggest using a dict object. Instead of holding everything as a list, you'll hold them as a key/value pair where they key is the name of the ingredient, and it's mapped to the total. Then you can consolidate the values for the same ingredient by using the ingredient name.

Furthermore, using a defaultdict will set all of them to 0 the first time you try to access them.

Note, I don't know how your ingredient type works, so this is pseudo-python

from collections import defaultdict

ingredient_totals = defaultdict(lambda ingredient_name : [new ingredient with ingredient_name, and 0 amount])

for ingredient in eating:
    ingredient_totals[ingredient.getName()].add(ingredient)

new_eating = list(d.values())
# Maybe sort new_eating

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