列表中字母的所有可能组合,从 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——所有可能的组合。
P.S。 bin(i)
通常比进行位操作更快,但我不确定添加的 zfill
.
是否仍然成立
目前正在尝试创建一个列表中这 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——所有可能的组合。
P.S。 bin(i)
通常比进行位操作更快,但我不确定添加的 zfill
.