簡體   English   中英

在 Python 中通過重復查找列表的所有組合

[英]Finding all combinations of a list in Python with repetition

我正在尋找並打印長度為 5 的集合 (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12) 的所有可能組合。應該有 13 個選擇 5組合 (6188) 因為順序無關緊要,並且允許重復。 我找到了這段代碼並正在使用它:

    from itertools import product
    for item in product([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], 
    repeat=5):
      print(item)

但是,這不會打印所有 6188 種組合。 試圖弄清楚如何調整代碼,使其吐出所有組合。

您想要的是使用combinations_with_replacement正如@Dani Mesejo 評論的那樣。
從文檔:

從輸入迭代中返回元素的 r 個長度子序列,允許單個元素重復多次。

from itertools import combinations_with_replacement

l = list(combinations_with_replacement([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], 5))
print(len(l))  # 6188

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM