简体   繁体   中英

Generate all n digit numbers using itertools, with bounds on range of 1st digit

I want to generate all n-digit numbers, such that the first digit goes from 1 to 7, and the rest can be between 0 and 9.

I wrote the generator for a general 7-digit generator, but I don't know how I might restrict the first digit to go only uptil 7.

import itertools
roll = []
for i in itertools.product([str(i) for i in xrange(1,10)], repeat=7):
    roll.append(''.join(i))
print roll

Here is a working solution. The first step is to create a 6 digit number. Then, I prefix it by all the numbers between 1 and 7 and append it to roll .

roll = []
for i in itertools.product([str(j) for j in xrange(1,10)], repeat=6):
    roll += [str(j)+''.join(i) for j in xrange(1,8)]
print roll

Note that itertools is not needed at all to generate this sequence, a simple one-liner would be enough:

roll = [str(i) for i in xrange(1000000, 8000000)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM