![](/img/trans.png)
[英]creating a list of all possible combination from a given list of words in python
[英]All possible combination of lists for a given list
我想要給定大小的列表的所有可能組合。 例如,我有一個給定的列表 K,例如K = [3, 5, 2]
。 使用以下代碼,我得到了我想要的。 但是,我如何將它推廣到給定大小的任何列表,而不僅僅是添加 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)
itertools庫通常可以幫助解決此類問題。 特別是itertools.product()
,使用*
向其傳遞范圍列表或迭代器:
list(itertools.product(*(range(n) for n in K))
或者
list(itertools.product(*map(range, K)))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.