问题
I'm trying to build a function that:
- accepts as an argument a list of positive integers of length n and
- returns a list of all lists of length n consisting of non-negative integers with the following property:
- for a list
lst
it holds that for all indices i,lst[i] ≤ upper bound[i]
- for a list
For example, if the input list was [1, 1, 2]
, then the output would be
[ [ 0 , 0 , 0 ] ,
[ 0 , 0 , 1 ] ,
[ 0 , 0 , 2 ] ,
[ 0 , 1 , 0 ] ,
[ 0 , 1 , 1 ] ,
[ 0 , 1 , 2 ] ,
[ 1 , 0 , 0 ] ,
[ 1 , 0 , 1 ] ,
[ 1 , 0 , 2 ] ,
[ 1 , 1 , 0 ] ,
[ 1 , 1 , 1 ] ,
[ 1 , 1 , 2 ] , ]
This is how far I've gotten:
def bounded_list(ub):
f = len(ub) * [0]
l = ub
res = [f]
while res[-1] != l:
res += [lex_suc1(res[-1], ub)]
return res
def lex_suc1(lst, ub):
res = lst[:]
i = len(res) - 1
while res[i] == ub[i]:
res[i] = 0
i -= 1
res[i] = ub[i]
return res
which gives the output:
[[0, 0, 0],
[0, 0, 2],
[0, 1, 0],
[0, 1, 2],
[1, 0, 0],
[1, 0, 2],
[1, 1, 0],
[1, 1, 2]]
I'm not able to understand how to include the missing lists, any help woul be great.
回答1:
this is an option:
from itertools import product
for lst in product(range(2), range(2), range(3)):
print(lst)
note that your list [1, 1, 2]
translates to range(2), range(2), range(3)
here.
or more directly:
res = list(product(range(2), range(2), range(3)))
# [(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 1, 0), (0, 1, 1), (0, 1, 2),
# (1, 0, 0), (1, 0, 1), (1, 0, 2), (1, 1, 0), (1, 1, 1), (1, 1, 2)]
or even:
lst = [1, 1, 2]
res = list(product(*(range(i+1) for i in lst)))
回答2:
You should take a look at itertools package and list comprehensions.
Then a solution is:
def f(upper_bounds):
return list(itertools.product(*(range(ub+1) for ub in upper_bounds)))
回答3:
You can use itertools.product for this.
from itertools import product
li = [1, 1, 2]
#Generate a list of possible numbers to generate the output from the given list
iters = [list(range(item+1)) for item in li]
#[[0, 1], [0, 1], [0, 1, 2]]
#Generate all possible combinations of these lists
print(list(product(*iters)))
The output will then be.
[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 1, 0),
(0, 1, 1), (0, 1, 2), (1, 0, 0), (1, 0, 1),
(1, 0, 2), (1, 1, 0), (1, 1, 1), (1, 1, 2)]
来源:https://stackoverflow.com/questions/55920343/create-a-list-that-contains-all-subsets-from-an-upperbound-but-where-lsti-%e2%89%a4-u