【问题标题】:Randomly replace N characters in a string with one letter用一个字母随机替换字符串中的 N 个字符
【发布时间】:2013-04-09 19:44:48
【问题描述】:

所以我有一个 DNA 序列文件,我的目标是用字母 M 随机替换序列中的 5 个核苷酸。

即。 dna1.txt 的序列为 ACTGGCTACATTG。

我想让 ACMGGCTACATTG 看起来像 ACMMGCMMCATMG 或类似的东西。

我知道如何一次替换一个字母,但不会替换多个。

dna1 = open ("dna1.txt","r")
data1 = dna1.read()

from random import randint, choice

def Mutated_DNA(data1):
    dna_list = list(data1)
    mutation_site = randint(0, len(dna_list)-1)
    dna_list[mutation_site] = choice(list('M'))        
    return ''.join(dna_list) 

print (Mutated_DNA(data1))

我该怎么办?

【问题讨论】:

    标签: python string random replace


    【解决方案1】:

    如果你想用新的东西替换 exactly 5 个字符,那么我认为最简单的方法是从可能的位置进行采样,然后准确地更改这些位置。例如:

    from random import sample
    
    def mutate(s, num, target):
        change_locs = set(sample(range(len(s)), num))
        changed = (target if i in change_locs else c for i,c in enumerate(s))
        return ''.join(changed)
    

    例如

    >>> mutate('ABC', 2, 'M')
    'MMC'
    >>> mutate('ABC', 2, 'M')
    'AMM'
    >>> mutate('ABC', 2, 'M')
    'MMC'
    >>> mutate('ABC', 2, 'M')
    'MBM'
    

    def mutate(s, num, target):
        change_locs = sample(range(len(s)), num)
        new_s = list(s)
        for change_loc in change_locs:
            new_s[change_loc] = target
        return ''.join(new_s)
    

    等等

    【讨论】:

      猜你喜欢
      • 2015-07-05
      • 2021-06-12
      • 2017-08-06
      • 2017-04-01
      • 1970-01-01
      • 2017-10-16
      • 2017-05-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多