- 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
- New Snippet! by Antoliny0919 4 days, 17 hours ago
- Add Toggle Switch Widget to Django Forms by OgliariNatan 2 months, 3 weeks ago
- get_object_or_none by azwdevops 6 months, 2 weeks ago
- Mask sensitive data from logger by agusmakmun 8 months, 1 week ago
- Template tag - list punctuation for a list of items by shapiromatron 1 year, 10 months ago
Comments
Please login first before commenting.