[英]All possible combination of lists for a given list
I would like to have all possible combinations of lists of a given size.我想要给定大小的列表的所有可能组合。 Lets say for example, I have a given list K, such as K = [3, 5, 2]
.例如,我有一个给定的列表 K,例如K = [3, 5, 2]
。 With the following code I get what I desire.使用以下代码,我得到了我想要的。 But how do I generalize this for any list of a given size, without just adding for loops?但是,我如何将它推广到给定大小的任何列表,而不仅仅是添加 for 循环?
assignment= []
for l in range(K[0]):
for m in range(K[1]):
for n in range(K[2]):
a = [l,m,n]
assignment.append(a)
The itertools library can often help with things like this. itertools库通常可以帮助解决此类问题。 itertools.product()
in particular, using *
to pass it a list or iterator of ranges:特别是itertools.product()
,使用*
向其传递范围列表或迭代器:
list(itertools.product(*(range(n) for n in K))
or或者
list(itertools.product(*map(range, K)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.