Python 删除字符串中的字符从包含原始字符的列表中替换为其他字符
这应该是模拟突变。我不明白如何选择一个不同的基(来自TCAG),以确保基确实发生了变化,正如doctype所提到的那样 编辑: 上述代码的另一个版本具有相同的功能:Python 删除字符串中的字符从包含原始字符的列表中替换为其他字符,python,Python,这应该是模拟突变。我不明白如何选择一个不同的基(来自TCAG),以确保基确实发生了变化,正如doctype所提到的那样 编辑: 上述代码的另一个版本具有相同的功能: 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 rep
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
需要明确的是,我的问题是如何用不同的基替换基?字符串在python中是不可变的,您应该重新分配从
基返回的字符串。replace(base“”)
到基
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:])
行
bases.replace(base',)
实际上不会更改bases
字符串。要更改base
字符串,必须设置base=base.replace(base.)
。自己测试一下
bases = bases.replace(base, '')
从这里开始,现在可能的碱基列表已经减少到只有突变的碱基,函数随机选择一个碱基与
碱基[randint(0,2)]
,并将其附加到新序列中。考虑将print语句交错到代码中,您可以看到它在做什么。以下是算法:
- 在字符串中选择一个随机索引。另存为“位置”
- 将该索引处的字符另存为“base”
- 在列表“TCAG”中,将字符“base”替换为空字符串,并将该列表另存为“base”(这样它将包含索引“position”中不包含的每个base)
- 从“基础”中选择一个随机字符,并将该字符另存为“新基础”。(因此,它将是移除最初随机拾取的基础后剩下的三个基础之一。)
- 返回三个字符串的串联:原始字符串到但不包括“position”、“newbase”,以及原始字符串到但不包括“newbase”
它不编辑字符串——它从旧字符串的两部分加上新的基创建一个新字符串,并返回该字符串。我不懂……代码可以工作;我只是不知道怎么做。具体请参见
newbase
行。假设我们有一个ATTGC序列。选择要更换的位置3(G)。代码如何确保位置3成为A、T或C?但我上面的代码确实有效;它每次都用其他三个基中的一个替换一个随机基。它用于替换G
s,因为newbase=bases[randint(0,2)]
只是从bases[0:3]=“TCA”
中选择一个随机基。如果您在底部为T
的另一个位置尝试代码。我保证,如果您在尝试替换T
时运行它100次,它有时会将T
替换为T
。这不是真的。我已经运行过几次了;每次用不同的基替换随机基时(除其自身外,即a不替换为a)。试试看:使用名称(“attgccgtaatgccgta”)随机替换\u base\u。
我做到了。你的第三点让它点击。谢谢。
bases = 'ACGT'
base = 'A'
print bases #prints 'ACGT'
bases.replace(base, '')
print bases #prints 'ACGT'
bases = bases.replace(base, '')
print bases #prints 'CGT'