Задать вопрос

Тел: +7 965 3737 888

521

Просмотров

3

Ответов

partition template filters

A couple of useful template filters for splitting a list (or QuerySet) up into rows or columns.

Вопрос полезен? Да0/Нет0
file_3797.py(4.0Кб)
None

Ответы (3):

Ответsmileychris:30.12.2007
Ответ полезен? Да0/Нет0

Actually, I notice from the comments that snippet 6 has a number of problems.

I have updated this snippet to fix all the problems noted there (complete with doctests ;))

Ответlgiordani:29.05.2012
Ответ полезен? Да0/Нет0

What about partitioning with a fixed lenght?

@register.filter
def partition_len(thelist, n):
    """
    Break a list into pieces with a maxmimum specified length.
    The last list may be shorter than the rest if the list doesn't
    break cleanly. That is::

        >>> l = range(10)

        >>> partition(l, 2)
        [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]]

        >>> partition(l, 3)
        [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]

    """
    try:
        n = int(n)
        thelist = list(thelist)
    except (ValueError, TypeError):
        return [thelist]
    return (thelist[i:i+n] for i in xrange(0, len(thelist), n))

Ответcarlospero:31.12.2008
Ответ полезен? Да0/Нет0

To have n number of columns with items in order across the rows, I added a "columns_across" function copied from "columns" but returns this instead:

return [thelist[n*i:n*(i+1)] for i in range(split)]