简体   繁体   English

如何在Python中记录返回列表

[英]How to document a returned list in Python

I have a piece of code that scrapes a college timetable webpage and generates a list of lists of lists (of lists) like so: 我有一段代码可以刮擦大学时间表的网页,并生成列表列表的列表,如下所示:

[[[[start_time, end_time], [module_code, period_type, {period_number}], [room_code]], {next modules...}],{next_days...}]

If I wanted to document this kind of returned data in Python (and possibly Java or other languages) would there be a best practice for doing so? 如果我想用Python(可能还有Java或其他语言)记录这种返回的数据,是否有最佳实践呢?

Note: I've looked at PEP but haven't been able to find anything related to this 注意:我已经查看了PEP,但找不到与此相关的任何内容

You create simple classes to hold your data instead of using nested lists: 您创建简单的类来保存数据,而不使用嵌套列表:

 class TimeTableEntry(object):
     def __init__(self, start, end, module, room):
         self.start = start
         self.end = end
         self.module = module
         self.room = room

Then document that your method returns a list of those. 然后记录您的方法返回这些列表。 The added advantage is that now you can add additional methods on these objects. 另一个好处是,现在您可以在这些对象上添加其他方法。 Add a __str__ method for easy display. 添加__str__方法以便于显示。 Etc. 等等。

Most of all, you can document these entry objects far more clearly than you could document a nested structure of primitive types. 最重要的是,与记录原始类型的嵌套结构相比,您可以更清楚地记录这些条目对象。

This sort of structure is better modeled as a dictionary; 这种结构最好建模为字典。 with the key being the room code. 钥匙是房间代码。 Each room code key holds a list, and this list has tuples that represent each course/event. 每个房间代码键都有一个列表,该列表具有表示每个课程/事件的元组。

schedule = dict()
schedule['room_1'] = [(start_time,end_time,module_code,period_type,..),
                      (start_time,end_time,module_code,period.....),
                      ...
                     ]
schedule['room_2'] = [ ... ] # as above

This makes it easier to document and also gives you the ability to do things like: 这使记录变得更容易,并且使您能够执行以下操作:

for i in schedule:
   print '{0} events scheduled for room {1}".format(len(schedule[i]),i)

Here is how you could possibly document it: 这是您可能如何记录的方法:

def foo(bar):
    '''
    Does some magic with `bar`.  Cats may be harmed and
    the space time continuum may be disturbed if you pass in
    silly things like None.

    Args:
        bar: The best name for a variable since foo.

    Returns:
        A dict mapping keys to the room and rows representing
        the room's schedule. A row is represented as a list.
        Each element of the list is a tuple of strings representing
        and event. For example:

        {'room_1': [(start_time,end_time,module_code,period_type,..)]}
    '''

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM