【问题标题】:Generate all combinations of nucleotide k-mers between range(i, j)生成范围(i,j)之间的所有核苷酸 k-mer 组合
【发布时间】:2016-03-17 05:17:36
【问题描述】:

我需要生成长度在 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,这不起作用。

提前致谢!

【问题讨论】:

    标签: python combinations permutation bioinformatics itertools


    【解决方案1】:

    如果你想找到所有的组合,你应该使用.product(),因为.permutations()不会产生像AAAAA或AATGC这样的重复核苷酸。试试这个:

    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 有一个更好的名称,而不是同一模块中的相关功能吗?不过严肃的评论,product 需要一个 kwarg repeat 可能应该在这里使用。
    【解决方案2】:

    另一种生成方式是使用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)
    

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-29
        相关资源
        最近更新 更多