簡體   English   中英

列表中字母的所有可能組合,從1到20-Python

[英]All possible combinations of letters from a list, from 1 to 20 - python

當前正在嘗試使它創建列表中這20個字母的所有可能組合(無重復)

letters = ['G','A','L','M','F','W','K','Q','E','S','P','V','I','C','Y','H','R','N','D','T']

combinations = [''.join(i) for i in itertools.combinations(letters,r=20)]

我正在尋找的輸出是類似這樣的列表:

combinations = ['G','A','L','M','F','W','K','Q','E','S','P','V','I','C','Y','H','R','N','D','T',GG,GA,GL,GM... ...GALMFWKQESPVICYHRNDT]

您可以在列表推導中使用嵌套循環來遍歷所有可能的長度:

letters = ['G','A','L','M','F','W','K','Q','E','S','P','V','I','C','Y','H','R','N','D','T']

combinations = [''.join(i) for j in range(1,len(letters) + 1) for i in itertools.combinations(letters,r=j)]

這是一種方法:

letters = ['G','A','L','M','F','W','K','Q','E','S','P','V','I','C','Y','H','R','N','D','T']

def gen_combinations(opts):
    for index in range(2 ** len(opts)):
        mask = bin(index)[2:].zfill(len(opts))
        selected = [o for (o,m) in zip(opts, mask) if m == '1']
        yield ''.join(selected)

如果您只希望一些可能性:

for (i,x) in enumerate(gen_combinations(letters)):
    print(x)
    if i > 10: break

輸出:

# The empty set
T
D
DT
N
NT
ND
NDT
R
RT
RD
RDT

如果您都想要它們:

all_combinations = list(gen_combinations(letters))
print(len(all_combinations))    # 1048576

它使用一個生成器,該生成器查看20位數字(在這種情況下)的二進制表示形式,如果位為1,則將該項目添加到該迭代的輸出列表中。

將有2 ^ len(opts)個列表元素-在這種情況下為2 ^ 20-所有可能的組合。

PS bin(i)通常比執行位操作更快,但是我不確定添加的zfill是否仍然適用。

暫無
暫無

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

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