[Tutor] Searching a text file's contents and comparing them toa list

Luke Paireepinart rabidpoobear at gmail.com
Wed Jul 14 21:23:19 CEST 2010


You already know how to store multiple vars -- use lists! Just create a blank one before your loop and append() to it. Also you might think of a generic way to do this without relying on separate variables for each aisle, what if your store has 30 aisles? Hint: lists can contain any python object, even other lists.

Sent from my iPhone

On Jul 14, 2010, at 2:05 PM, Eric Hamiter <ehamiter at gmail.com> wrote:

> Follow-up question: My code is now this:
> 
> aisle_one = ["chips", "bread", "pretzels", "magazines"]
> aisle_two = ["juice", "ice cream"]
> aisle_three = ["asparagus"]
> 
> def find_groceries():
>    grocery_list = open("grocery_list.txt", "r")
>    for line in grocery_list.readlines():
>        line = line.strip()
>        if line in aisle_one:
>            first_run = "%s" % line + " - aisle one.\n"
>        elif line in aisle_two:
>            second_run = "%s" % line + " - aisle two.\n"
>        elif line in aisle_three:
>            third_run = "%s" % line + " - aisle three.\n"
>        else:
>            out_of_luck = "%s" % line
>    print first_run, second_run, third_run
>    print "I couldn't find any %s. Add it to the database. \n" % out_of_luck
>    grocery_list.close()
> 
> find_groceries()
> 
> 
> I can see that the variables first_run, second_run and third_run are
> writing over themselves while looping, which is logical, but this is
> not what I want. If I simply print them immediately instead of storing
> them as variables, all items will print, but not in the order I wish.
> The ultimate goal of the program will be to sort the items based on
> aisle locations. Is there an efficient way to do this?
> 
> I think I want some kind of incremental counter going on in the loop
> to prevent them from overwriting themselves, or a way to store
> multiple variables, but I'm not sure how to do that.
> 
> Thanks for any ideas. This list and all its participants are super
> helpful-- I'm very appreciative.
> 
> Eric
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


More information about the Tutor mailing list