簡體   English   中英

如何在不使用任何庫(如 Itertools)的情況下在 Python 中查找字符串或列表的所有組合?

[英]How To Find All Combinations Of String OR List In Python Without Using Any Libraries Like Itertools?

所以我基本上試圖生成一個字符串(長度為 Y)的所有可能組合(長度為 X),其中 Y 大於或等於 X。

例如:

For The Given String "ABC" All The Combinations With Size 2 Are:
    ["AA", "AB", "AC", "BA", "BB", "BC", "CA", "CB", "CC"]

注意:無論組合的長度或字符串的長度如何,我都應該能夠使用相同的代碼生成所有組合。

我試圖找到解決方案,但找不到邏輯。

提前致謝

如果您查看文檔,您將看到與itertools. product大致相當的本機 Python 代碼itertools. product 給出itertools. product

from itertools import product

# From https://docs.python.org/3/library/itertools.html#itertools.product
def product_no_lib(*args, repeat=1):
    # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
    # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
    pools = [tuple(pool) for pool in args] * repeat
    result = [[]]
    for pool in pools:
        result = [x + [y] for x in result for y in pool]
    for prod in result:
        yield tuple(prod)

def main():
    s = 'ABC'
    itertools_product = [''.join(p) for p in product(s, repeat=2)]
    cartesian_product = [''.join(p) for p in product_no_lib(s, repeat=2)]
    print(itertools_product)
    print(cartesian_product)

if __name__ == '__main__':
    main()

輸出:

['AA', 'AB', 'AC', 'BA', 'BB', 'BC', 'CA', 'CB', 'CC']
['AA', 'AB', 'AC', 'BA', 'BB', 'BC', 'CA', 'CB', 'CC']

暫無
暫無

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

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