Anticollate? Disinterleave?

 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. Group sequence into rows and columns for a TABLE by davidwtbuxton 2 years, 3 months ago
  2. Yet another list partitioning filter by AndrewIngram 4 years ago
  3. Action that respects the filters in changeview_list by grillermo 7 months, 2 weeks ago
  4. Vertical and Horizontal Line to geraldo report by lucmult 3 years ago
  5. Showell markup--DRY up your templates by showell 3 years, 5 months ago

Comments

(Forgotten your password?)