Reputation: 616
I'm a newbie so please bear with me if I've overlooked something basic, but I'm trying to make site that lists yoga classes for my friend's yoga studio, which conceptually should look something like this:
Monday
Dynamic Yoga with Mary 6pm
Soft yoga with Susie 8pm
Wednesday
Hatha yoga with Bob 5pm
Hot yoga with Alice 7pm
So I want to fetch the list of classes, then see if there is a yoga class on Monday. If there is one I add 'Monday' to the list and all the Monday classes, and so on with all the other days.
Problem:
My code so far appends all the days where there are yoga classes, but then adds all of the classes from the whole week to every day, when they should only add the classes that corresponds to each day.
I.e. when it should be:
Monday_list = [Monday, [[Class1Monday],[Class2Monday]]
it is instead:
Monday_list [Monday, [[CLass1Monday],[CLass2Monday],[CLass1Tuesday],[CLass2Tuesday]]]
This is my code (It's on Google App Engine, which may explain some oddities in the code...):
def get_classes():
weekly_classes = []
d = {1: 'Monday',
2: 'Tuesday',
3: 'Wednesday',
4: 'Thursday',
5: 'Friday',
6: 'Saturday',
7: 'Sunday'}
yoga_classes = Schema.all() #appengine DB request
if yoga_classes:
#list that will be sent to template
for n in range(1,8):
day_classes = []
for e in yoga_classes:
if e.weekday == n:
day = d[n]
class_output = [str(e.name),
str(e.teacher),
str(e.description)
]
day_classes.append(class_output)
day_output = [day,day_classes]
weekly_classes.append(day_output)
self.response.out.write(weekly_classes)
Upvotes: 0
Views: 74
Reputation: 2868
Here's some more pythonic code, leveraging itertools
. The data is sorted by the day as required by groupby()
, then grouped. I have found that any use of the range function indicates that you're doing something that is more C than python, and there's probably a cleaner way to do it. Note that the vast majority of this code is just setting up the dummy data to work with.
class Yoga():
def __init__(self,weekday,name,teacher,description):
self.weekday=weekday
self.name=name
self.teacher=teacher
self.description=description
def __str__(self):
return "%s yoga with %s %s" % (self.name,self.teacher,self.description)
def __repr__(self):
return str(self)
# just make up some data to work with
yoga_classes = (Yoga(1,"dynamic","mary","6pm"),
Yoga(1,"soft","susie","8pm"),
Yoga(3,"hatha","bob","5pm"),
Yoga(3,"hot","alice","7pm"))
daylookup = (None,"Monday","Tuesday","Wednesday",
"Thursday","Friday","Saturday","Sunday")
import itertools
def get_classes():
weekly_classes = []
ycsorted = sorted(yoga_classes,key=lambda x: x.weekday)
for k,g in itertools.groupby(ycsorted,key=lambda x: x.weekday):
weekly_classes.append((daylookup[k],tuple(g)))
return weekly_classes
import pprint
pprint.pprint(get_classes())
Upvotes: 2