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

3

我正在尝试生成一个长度为四个字符的所有可能DNA序列的列表,这四个字符为ATCG。总共有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))

然而,当 li = [] 时,运行 allCombinations('ATCG', li) ,然后使用 list(set(li)) 仍然只会生成136个唯一的序列,而不是256个。

必须有一种简单的方法来解决这个问题,也许是生成一个幂集,然后过滤长度为4的子集?


1
itertools.product('ATCG', repeat=4) - ayhan
Post as answer and ill accept - izaak_pyzaak
这非常相似。但我认为链接中的用户正在询问字符串中组合的滑动窗口。 - izaak_pyzaak
@izaak_pyzaak,这基本上与DeepSpace的答案相同,只是更简短。因此,您可以接受他们的答案,他们可能会编辑答案以包括此替代方法。 - ayhan
1
没有加载的模块,纯Python代码一行搞定:sorted([ a+b+c+d for a in 'ATCG' for b in 'ATCG' for c in 'ATCG' for d in 'ATCG' ]) - nigel222
2个回答

6
您可以通过使用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

但是它返回元组,所以如果你想要字符串:

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

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

谢谢,伙计。我很快会接受的。 - izaak_pyzaak
2
[''.join(x) for x in itertools.product(a, repeat=4)] 的列表推导式。 - Pax Vobiscum

0

你可以试试这个

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)

这真的不太可扩展,也不是寻找itertools方法的问题的好答案。 - John Coleman
你说得对,确实不是最好的选择。但有时候你必须使用当前情况下最好的选项,而不仅仅是选择最可扩展的选项。这个相当容易理解。 - Pax Vobiscum
这个相对容易理解。但要理解这段代码的作用,需要在脑海中同时记住并跟踪8个不同的变量。 - DeepSpace
不,我不会将这个作为“复制+粘贴”的例子,然而4个嵌套的for循环的概念并非编程的,而是数学的,这个概念是基本组合学。再次思考回答这个问题的原因不是如何,而是为什么,是为了得到一个可行的一行代码?理解“itertools”?或者只是学校的练习... - Pax Vobiscum

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接