""" Split a list of items into a table. Example usage in a Kid/Genshi template (don't forget to add the tabularize function to the template context): <table> <tr py:for="row in tabularize(users, 4, vertical=True)"> <td py:for="user in row"> <a py:if="user" href="/users/${user.id}"> ${user.name} </a> </td> </tr> </table> """ def tabularize(items, column_count, vertical=False): """Split a list of items into a table.""" row_count = int(math.ceil(len(items) / float(column_count))) table = [[None] * column_count for i in xrange(row_count)] for i, item in enumerate(items): if vertical: x, y = divmod(i, row_count) else: y, x = divmod(i, column_count) table[int(y)][int(x)] = item return table