生成范围 (i, j) 之间的核苷酸 k-mers 的所有组合

Generate all combinations of nucleotide k-mers between range(i, j)

我需要生成长度在 5-15 之间的所有可能核苷酸组合的列表。

nucleotides = ['A', 'T', 'G', 'C']

预期结果:

AAAAA
AAAAT
AAAAC
AAAAG
AAATA
AAATT
...
AAAAAAAAAAAAAAA
AAAAAAAAAAAAAAT
etc.

我试过了:

for i in range(5,16):
    for j in itertools.permutations(nucleotides, i):
        print j

但是如果 len(nucleotides) < i.

则这不起作用

提前致谢!

如果你想找到所有的组合,你应该使用.product() as .permutations() 无论如何不会产生像AAAAAAATGC这样重复的核苷酸。试试这个:

for i in range(5, 16):
    combinations = itertools.product(*itertools.repeat(nucleotides, i))
    for j in combinations:
        print(j)

更新:正如@JaredGoguen 提到的,repeat 参数也可以在这里使用:

combinations = itertools.product(nucleotides, repeat=i)

您可以生成的另一种方法是使用 combinations_with_replacement(),它允许重复:

import itertools

result=set()
nucleotides = ['A', 'T', 'G', 'C']
for i in range(5,16):
    for j in itertools.combinations_with_replacement(nucleotides, i):
        print(''.join(j))

然后您可以进一步排列它们以获得所有变体,如下所示:

import itertools

result=set()
nucleotides = ['A', 'T', 'G', 'C']
for i in range(5,16):
    for j in itertools.combinations_with_replacement(nucleotides, i):
        for k in itertools.permutations(j):
            result.add(''.join(k))
for i in result:
    print(i)

为了增加 Selcuk 的答案,这里有一个生成可迭代对象的单行代码。

from itertools import chain, product

chain(product(nucleotides, repeat=i) for i in range(5, 16))