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
- Template tag - list punctuation for a list of items by shapiromatron 10 months ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 1 week ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 5 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.