[Tutor] Searching a text file's contents and comparing them toa list
Eric Hamiter
ehamiter at gmail.com
Wed Jul 14 21:05:43 CEST 2010
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
More information about the Tutor
mailing list