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 5 years, 8 months ago
  2. Anticollate? Disinterleave? by lemonlaug 3 years, 4 months ago
  3. Redirect with change list with filters intact with admin actions by AndrewIngram 3 years, 10 months ago
  4. A couple of template filters for partitioning lists by jacobian 6 years, 3 months ago
  5. Group sequence into rows and columns for a TABLE by davidwtbuxton 2 years, 3 months ago

Comments

(Forgotten your password?)