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. FileField having auto upload_to path by junaidmgithub 2 days ago
  2. LazyPrimaryKeyRelatedField by LLyaudet 1 week, 2 days ago
  3. CacheInDictManager by LLyaudet 1 week, 2 days ago
  4. MYSQL Full Text Expression by Bidaya0 1 week, 3 days ago
  5. Custom model manager chaining (Python 3 re-write) by Spotted1270 2 weeks, 2 days ago

Comments

Please login first before commenting.