[Tutor] Searching a text file's contents and comparing them toalist
christopher.henk at allisontransmission.com
christopher.henk at allisontransmission.com
Thu Jul 15 00:12:37 CEST 2010
Eric Hamiter wrote on 07/14/2010 04:57:57 PM:
> Thanks for the pointers! This is now working, albeit probably ugly and
clunky:
>
>
> aisle_one = ["chips", "bread", "pretzels", "magazines"]
> aisle_two = ["juice", "ice cream"]
> aisle_three = ["asparagus"]
>
> def find_groceries():
> with open("grocery_list.txt") as grocery_list:
>
> first_trip = ["Located on aisle 1: "]
> second_trip = ["Located on aisle 2: "]
> third_trip = ["Located on aisle 3: "]
> no_trip = ["Not found in the database: "]
>
> for item in grocery_list:
> item = item.rstrip()
> if item in aisle_one:
> first_trip.append(item)
> elif item in aisle_two:
> second_trip.append(item)
> elif item in aisle_three:
> third_trip.append(item)
> else:
> no_trip.append(item)
>
> sorted_list = first_trip, second_trip, third_trip, no_trip
> print sorted_list
>
> find_groceries()
>
>
> Last question (for today, at least): Right now, the output is less
> than aesthetically pleasing:
>
> (['Located on aisle 1: ', 'bread', 'magazines'], ['Located on aisle 2:
> ', 'juice', 'ice cream'], ['Located on aisle 3: ', 'asparagus'], ['Not
> found in the database: ', 'butter', 'soap'])
>
> How can I format it so it looks more like this:
>
> Located on aisle 1:
> bread
> magazines
>
> Located on aisle 2
> [etc...]
>
>
> I tried putting "\n" into it but it just prints the literal string.
> I'm sure it has to do with the list format of holding multiple items,
> but so far haven't found a way to break them apart.
>
your sorted_list is a tuple of lists so when you print it python is
showing you that structure.
You want the contents of each of those lists printed in a more readable
format, so you need to loop through the tuple to get each list(trips down
an aisle)and then within that loop, loop through each list to print each
item.
in pseudo code to output like you suggest
for each aisle_list in sorted_list
for each item in the aisle_list
print the item
print the space (to separate the aisles, this is part of the loop
through the tuple, so will run once for each aisle)
Instead of replacing the print statement with the above, I would have this
as another function which takes sorted_list as a parameter, changing
find_groceries to return sorted_list instead of printing it. This keeps
the two tasks separate and easier to understand and/or debug.
so the last lines of your program are:
sorted_list=find_groceries()
print_shoppinglist(sorted_list)
instead of just calling find_groceries()
Chris
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100714/86f262cf/attachment.html>
More information about the Tutor
mailing list