Django/Python: How can I make the following number increment (not in database)

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-04 19:25:16

All the leading zeroes are just formatting.

>>> "%012d" % ( 1, )
'000000000001'
>>> "%012d" % ( 2, )
'000000000002'

Use an ordinary integer and format it to have lots of leading zeroes.

There's actually a super tricky way to do this using the itertools library and a generator function.

from itertools import product, imap

def stringdigit(num_digits=10, start = None):
    """A generator function which returns string versions of a large iterated number with
    leading zeros. start allows you to define a place to begin the iteration"""
    treatfun = lambda x: ''.join(x)
    for n in imap(treatfun, product('0123456789', repeat = num_digits)):
        if start == None or n > start:
            yield n

This creates an iterator which will return the "zero-padded string form" that you need. It works using the product function which iteratively returns repeated combinations from an iterable in "sorted order". The num_digits argument specifies how many total digits you would like returned. start specifies a place to begin the iteration from (say if you wanted to start from 1111111).

product comes with the python 2.6 release. If your using something before that for some reason then use this as the product definition. Taken from the docs here.

def product(*args, **kwds):
    # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
    # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
    pools = map(tuple, args) * kwds.get('repeat', 1)
    result = [[]]
    for pool in pools:
        result = [x+[y] for x in result for y in pool]
    for prod in result:
        yield tuple(prod)

You can use this function in in a for-loop as an interator:

for num in stringdigit(num_digits = 7):
    #do stuff with num

Hope that helps. -Will

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!