删除字符串中的字符替换为包含原始字符的列表中的其他字符

2024-06-12 09:58:01 发布

您现在位置:Python中文网/ 问答频道 /正文

from random import randint

def replace_base_randomly_using_names(base_seq):
    """Return a sequence with the base at a randomly selected position of base_seq
    replaced by a base chosen randomly from the three bases that are not at that
    position."""
    position = randint(0, len(base_seq) - 1) # −1 because len is one past end
    base = base_seq[position]
    bases = 'TCAG'
    bases.replace(base, '') # replace with empty string!
    newbase = bases[randint(0,2)]
    beginning = base_seq[0:position] # up to position
    end = base_seq[position+1:] # omitting the base at position
    return beginning + newbase + end

这是用来模拟突变的。我不明白如何选择一个不同的基(来自TCAG)来确保基确实发生了变化,正如doctype提到的那样。你知道吗

编辑:

上述代码的另一个版本执行相同的操作:

def replace_base_randomly(base_seq):
    position = randint(0, len(base_seq) - 1)
    bases = 'TCAG'.replace(base_seq[position], '')
    return (base_seq[0:position] +
            bases [randint(0,2)] +
            base_seq[position+1:])

要清楚的是,我的问题是如何用一个不同的基地取代基地?你知道吗


Tags: thefrombaselendefwithpositionrandomly
3条回答

考虑将print语句交错放入代码中,您可以看到它在做什么。算法如下:

  • 在字符串中选择一个随机索引。另存为“位置”
  • 将该索引处的字符另存为“base”。你知道吗
  • 在列表“TCAG”中,将字符“base”替换为空字符串,并将该列表另存为“bases”(因此它将包含索引“position”处没有的每个基)。你知道吗
  • 从“bases”中选择一个随机字符,并将该字符另存为“newbase”。(因此,它将是移除最初随机选取的基础后剩下的三个基础之一。)
  • 返回三个字符串的串联:在“position”之前但不包括“newbase”的原始字符串,以及在“newbase”之后但不包括“newbase”的原始字符串

它不编辑字符串,而是从旧字符串的两部分加上新的基创建一个新字符串,并返回该字符串。你知道吗

字符串在python中是不可变的,您应该将从bases.replace(base, '')返回的字符串重新分配给bases。你知道吗

bases = bases.replace(base, '')

bases.replace(base, '')实际上并没有更改bases字符串。要更改bases字符串,必须设置bases = bases.replace(base, '')。你自己测试一下

bases = 'ACGT'
base = 'A'
print bases #prints 'ACGT'
bases.replace(base, '')
print bases #prints 'ACGT'
bases = bases.replace(base, '')
print bases #prints 'CGT'

从这里开始,现在可能的碱基列表已经减少到只有突变的碱基,函数随机选择一个带有bases[randint(0, 2)]的碱基并将其附加到新序列中。你知道吗

相关问题 更多 >