Yet another list partitioning filter

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
from django.template import Library

register = Library()

@register.filter
def partition(input, n):
    """
    Break a list into sublists of length ``n``. That is, 
    ``partition(range(10), 4)`` gives::
    
        [[1, 2, 3, 4],
         [5, 6, 7, 8],
         [9, 10]]
    """
    try:
        n = int(n)
        input = list(input)
    except (ValueError, TypeError):
        return [input]
    return [input[i:i+n] for i in range(0, len(input), n)]

More like this

  1. partition template filters by SmileyChris 4 years, 5 months ago
  2. A couple of template filters for partitioning lists by jacobian 4 years, 11 months ago
  3. Chunks template filter by oggy 3 years, 4 months ago
  4. table with n items per row using custom modulo tag by elgreengeeto 3 years, 2 months ago
  5. Additional Change List Columns by sansmojo 4 years, 6 months ago

Comments

(Forgotten your password?)