- 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
- Serializer factory with Django Rest Framework by julio 5 months, 3 weeks ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 6 months, 1 week ago
- Help text hyperlinks by sa2812 7 months, 1 week ago
- Stuff by NixonDash 9 months, 1 week ago
- Add custom fields to the built-in Group model by jmoppel 11 months, 2 weeks ago
Comments
Please login first before commenting.