Login

Yet another list partitioning filter

Author:
AndrewIngram
Posted:
May 12, 2009
Language:
Python
Version:
1.0
Score:
2 (after 2 ratings)

A simple template filter for breaking a list into sublists of a given length, you might use this on an ecommerce product grid where you want an arbitrary number of rows of fixed columns. Unlike the other partitioning filters I've seen, this doesn't try to distribute the rows evenly, instead it fills each row for moving onto the next.

This filter preserves the ordering of the input list.

 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. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 12 months ago

Comments

Please login first before commenting.