Login

Integer list to pattern function

Author:
marinho
Posted:
December 1, 2007
Language:
Python
Version:
.96
Tags:
list integer
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. Pattern to integer list function by marinho 7 years, 4 months ago
  2. Model Choices Helper by pmclanahan 5 years, 3 months ago
  3. Filter by first letter inclusion tag by slafs 4 years, 11 months ago
  4. SuperChoices by willhardy 6 years, 5 months ago
  5. Yet another SQL debugging facility by miracle2k 7 years, 8 months ago

Comments

Please login first before commenting.