Login

Anticollate? Disinterleave?

Author:
lemonlaug
Posted:
January 23, 2010
Language:
Python
Version:
1.1
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

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

Comments

Please login first before commenting.