长度为 4 的字符串中 DNA 字符的所有组合

all combinations of DNA characters in a string of length 4

我正在尝试用四个字符 ATCG 生成所有可能的长度为 4 的 DNA 序列的列表。总共有 4^4 (256) 种不同的组合。我包括重复,这样 AAAA 是允许的。 我看过 itertools.combinations_with_replacement(iterable, r) 但是,列表输出会根据输入字符串的顺序发生变化,即

itertools.combinations_with_replacement('ATCG', 4) #diff results to...
itertools.combinations_with_replacement('ATGC', 4)

因此,我尝试将 itertools.combinations_with_replacement(iterable, r)itertools.permutations()

结合起来

这样将 itertools.permutations() 的输出传递给 itertools.combinations_with_replacement()。定义如下:

def allCombinations(s, strings):
perms = list(itertools.permutations(s, 4))
allCombos = []
for perm in perms:
    combo = list(itertools.combinations_with_replacement(perm, 4))
    allCombos.append(combo)
for combos in allCombos:
    for tup in combos:
        strings.append("".join(str(x) for x in tup))

然而 运行 allCombinations('ATCG', li) 其中 li = [] 然后取 list(set(li)) 仍然只处理 136 个唯一序列,而不是 256 个。

一定有一个简单的方法可以做到这一点,也许生成幂集然后过滤长度为 4?

你可以试试这个

l = []

s = 'ATCG'

for a in s:
    n1 = a
    for b in s:
        n2 = n1 + b
        for c in s:
            n3 = n2 + c
            for d in s:
                l.append(n3+d)

您可以使用 product 来实现。它给出了传递的迭代的笛卡尔积:

a = 'ACTG'

print(len(list(itertools.product(a, a, a, a))))
# or even better, print(len(list(itertools.product(a, repeat=4)))) as @ayhan commented
>> 256

但它 returns 元组,所以如果你正在寻找字符串:

for output in itertools.product(a, repeat=4):
    print(''.join(output))

>> 'AAAA'
   'AAAC'
   .
   .
   'GGGG'