![](/img/trans.png)
[英]Python - Generating random dna sequences with Numpy, ValueError
[英]Generating random sequences of DNA
我試圖使用隨機數和隨機字符串在python中生成隨機的DNA序列。 但我只得到一個字符串作為我的輸出。 例如:如果我給出長度為5的DNA(String(5)),我應該得到一個輸出“CTGAT”。 同樣,如果我給String(4)它應該給我“CTGT”。 但我得到“G”或“C”或“T”或“A”; 即每次只有一個字符串。 誰有人可以幫我這個?
我嘗試了以下代碼:
from random import choice
def String(length):
DNA=""
for count in range(length):
DNA+=choice("CGTA")
return DNA
我會一次性生成字符串,而不是構建它。 除非Python聰明並優化字符串添加,否則它會將運行時復雜性從二次變為線性。
import random
def DNA(length):
return ''.join(random.choice('CGTA') for _ in xrange(length))
print DNA(5)
你回來太快了:
from random import choice
def String(length):
DNA=""
for count in range(length):
DNA+=choice("CGTA")
return DNA
如果你的return
語句在for
循環中,你將只迭代一次---你將退出函數return
。
從return
語句的Python文檔 :“ return將當前函數調用與表達式列表(或無)一起作為返回值。”
所以,將return
放在函數的末尾:
def String(length):
DNA=""
for count in range(length):
DNA+=choice("CGTA")
return DNA
編輯:這是一個加權選擇方法(它只適用於當前的字符串,因為它使用字符串重復)。
def weightedchoice(items): # this doesn't require the numbers to add up to 100
return choice("".join(x * y for x, y in items))
然后,你想在循環中調用weightedchoice
而不是choice
:
DNA+=weightedchoice([("C", 10], ("G", 20), ("A", 40"), ("T", 30)])
我已升級代碼以提供從0到100%的GC百分比分布。 上面的代碼總是產生50%的分布。
actg_distribution字符串可以是已知GC百分比的現有DNA序列的任何長度。 某個范圍的GC百分比是常見的用例。
import random
# Return random CGTA sequences, set minimum = maximum to get a specified length.
def random_length_dnasequence(minimum=25, maximum=10000, actg_distribution=None):
if (minimum == maximum):
length = minimum
else:
length = random.randint(minimum, maximum)
if (actg_distribution == None):
actg_distribution = ''.join(random.choice('cgta') for _x in xrange(7))
return ''.join(random.choice(actg_distribution) for _x in xrange(length))
def random_dnasequence(length, actg_distribution=None):
return random_length_dnasequence(length, length, actg_distribution)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.