[英]How to calculate the number of all possible combinations for a range of numbers from 1 to N?
[英]How to print all number combinations from specific set of numbers?
我正在嘗試從數字列表中獲取每個數字組合。
目前,我可以輕松地將其作為一個范圍,並且我可以在一組 5 個數字中獲得我想要的每個數字組合(打印在 5 個單獨的列中)。 我不知道該怎么做是如何從一個非常具體的數字列表中獲取每個數字組合,這些數字列表從現有代碼中打印出完全相同的格式。
下面是我在一個范圍內查找數字的代碼,它運行良好:
for range_numbers in combinations(list(range(1,20)), 5): #This gives me every 5 number combination without repeating numbers.
for nums in combinations(list(range(1,10)), 1): #this adds every combination of this range without repeating numbers, in a single column.
combined = range_numbers + nums
file_writer.writerow(combined)
count += 1
我想要的是產生完全相同的結果,但來自特定數字的列表,例如 5 個數字組合的 [2,3,5,7,9,12,13,15,19] 和 [3,7, 8,10] 用於添加的 1 個數字組合。
感謝您提供任何幫助,我在過去的 8 小時里一直在谷歌上搜索並試圖弄清楚這一點,感覺應該很容易,但我的大腦現在只是糊狀..
這是操作數的直接替換:
from itertools import combinations, product
large = [2,3,5,7,9,12,13,15,19]
small = [3,7,8,10]
for range_numbers in combinations(large, 5):
for nums in combinations(small, 1):
...
或許更好的是,按照 Guido 的意圖,使用product
在單個循環中執行此操作:
for combined in product( [list(combinations(large, 5)),
list(combinations(small, 1))] ):
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.