0

我是新手,所以如果我忽略了一些基本的东西,请多多包涵,但我正在尝试创建一个网站,列出我朋友的瑜伽工作室的瑜伽课程,从概念上讲,它应该看起来像这样:

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)
4

1 回答 1

2

这里有一些更多的 Pythonic 代码,利用itertools. 数据按照 的要求按天排序groupby(),然后分组。我发现对 range 函数的任何使用都表明您正在做的事情比 python 更多的是 C,并且可能有一种更简洁的方法来做到这一点。请注意,此代码的绝大多数只是设置要使用的虚拟数据。

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())
于 2013-02-27T01:59:17.930 回答