Login

Anticollate? Disinterleave?

Author:
lemonlaug
Posted:
January 23, 2010
Language:
Python
Version:
1.1
Tags:
filter partitioning every-other
Score:
0 (after 0 ratings)

This is yet another partitioning filter, but I wanted to be able to distribute my objects across two columns, and have them read from left to right, top to bottom. So if n = 2 this would return every other object from a queryset.

With gratitude to the author of snippet 6.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
"""
Template tags for working with lists.

You'll use these in templates thusly::

    {% load listutil %}
    {% for sublist in mylist|anticollate:"3" %}
        {% for item in mylist %}
            do something with {{ item }}
        {% endfor %}
    {% endfor %}
"""

from django import template

register = template.Library()

@register.filter
def anticollate(thelist, n):
    """
    Break a list into ``n`` pieces. Some lists (at the beginning) may be larger than the rest if
    the list doesn't break cleanly. That is::

    >>> l=range(10)
    >>> anticollate(l,3)
    [[0, 3, 6, 9], [1, 4, 7], [2, 5, 8]]
    >>> anticollate(l,4)
    [[0, 4, 8], [1, 5, 9], [2, 6], [3, 7]]
    >>> anticollate(l,5)
    [[0, 5], [1, 6], [2, 7], [3, 8], [4, 9]]
    """
    try:
        n = int(n)
        thelist = list(thelist)
    except (ValueError, TypeError):
        return [thelist]
    return [[thelist[j] for j in range(len(thelist)) if j%n==i] for i in range(n)] 

More like this

Comments

Please login first before commenting.