How to create a list of all possible lists with n elements consisting of integers from 1 to 10?

I am trying to create a set of test cases for a project that I am working on, and I would like to create all possible test cases and iterate over them (fast program, it won't take much time). All test cases should be a list of length 1-4, and each element in the list should be an integer from 0 to 10 inclusive. The first element in the list should be 0. Then the list of lists will be as follows:

[0] [0,0] [0,1] [0,2] [0,3] ... [0,10] [0,0,0] [0,0,1] [0,0,2] [0,0,3] ... [0,1,0] [0,1,1] [0,1,2] ... [0,10,10] ... [0,10,10,10] 

This is what I have so far, but it does not list the correct lists:

 test_list = [0] for length in range(2, 5): while len(test_list) < length: test_list.append(0) for position in range(1, length): for digit in range (0, 11): test_list[position] = digit print test_list 
+5
source share
3 answers

Efficient single line file with memory:

 import itertools size = 4 for x in map(list, itertools.chain(*(itertools.product([0], *[range(11)]*i) for i in range(size)))): print(x) 

You can change 4 with any other list size :)

0
source

or you can generate lists using a generator; thus you would not have the entire list in mind:

 from itertools import product def gen(): yield [0] for i in range(11): yield [0, i] for i, j in product(range(11), range(11)): yield [0, i, j] for i, j, k in product(range(11), range(11), range(11)): yield [0, i, j, k] for item in gen(): print(item) 

this seems to me readable enough, but not extensible (if you need longer lists) like the other answers here.

so here is the version where the list length is customizable:

 from itertools import product def gen(length): for l in range(length): for tpl in product(range(11), repeat=l): yield (0,) + tpl for item in gen(length=4): print(item) 

now this version returns tuples , not lists . in case this matters, you can display the return values ​​with list() .

+4
source

I would use itertools.product in lists of sizes 2, 3, 4 in a nested loop

 import itertools test_list = [0] for i in range(1,4): args = [list(range(0,11))] *i test_list += [[0]+list(x) for x in itertools.product(*args)] # display list for t in test_list: print(t) 
+2
source

Source: https://habr.com/ru/post/1261792/


All Articles