Login

Integer list to pattern function

Author:
marinho
Posted:
December 1, 2007
Language:
Python
Version:
.96
Score:
-1 (after 1 ratings)

This function can be util for transform pattern lists like these to strings:

>>> list_to_pattern([42, 43, 44, 45])
'42-45'

>>> list_to_pattern([15, 49, 50, 51, 52])
'15,49-52'

>>> list_to_pattern([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13])
'0-13'

You can use also the pattern to list function at http://www.djangosnippets.org/snippets/495/

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
def list_to_pattern(self, lst):
    ret = ''
    lst.sort()

    start = None
    # Starts from second item
    for i in range(1, len(lst)):
        # In sequence
        if lst[i] == lst[i-1] + 1:
            if start is None: start = lst[i-1]

            # Last item
            if i == len(lst) - 1:
                ret += ' %d-%d' %(start, lst[i])

        # Sequence broked
        else:
            # Last item
            if start is None:
                ret += ' %d' % lst[i-1]
            else:
                ret += ' %d-%d' %(start, lst[i])

    return ret.strip().replace(' ', ',')

More like this

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

Comments

Please login first before commenting.