我是新手所以如果我忽略了一些基本的东西,请耐心等待我,但我正在努力为我朋友的瑜伽工作室制作瑜伽课程,其概念应该是这样的:
Monday
Dynamic Yoga with Mary 6pm
Soft yoga with Susie 8pm
Wednesday
Hatha yoga with Bob 5pm
Hot yoga with Alice 7pm
所以我想获取课程列表,然后看星期一是否有瑜伽课。如果有的话,我会在列表和所有星期一课程中添加“星期一”,依此类推其他所有日期。
问题:
到目前为止,我的代码附加了瑜伽课程的所有日期,但随后将所有课程从一周添加到每一天,此时他们应该只添加与每天相对应的课程。
即。什么时候应该:
Monday_list = [Monday, [[Class1Monday],[Class2Monday]]
相反:
Monday_list [Monday, [[CLass1Monday],[CLass2Monday],[CLass1Tuesday],[CLass2Tuesday]]]
这是我的代码(它在Google App Engine上,可以解释代码中的一些奇怪内容......):
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)
答案 0 :(得分:2)
这里有一些pythonic代码,利用itertools
。数据按groupby()
的要求按日排序,然后进行分组。我发现使用range函数表明你正在做的事情比Cthon更多,而且可能有一种更简洁的方法。请注意,绝大多数此代码只是设置要处理的虚拟数据。
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())