[英]Begginer in Python - RNA transcript for a list of DNA sequences
我對 Python 很陌生,我正在嘗試獲取 DNA 序列的 RNA 轉錄。 盡管我能夠對單個 DNA 序列執行此操作,但我正在嘗試找到一種方法來為 DNA 序列列表執行此操作。 我希望你能給我一些指導。
# Given this DNA sequence, get the RNA sequence:
dna = 'ACCTGACT'
# Defining the RNA transcription formula
def to_rna(dna_strand):
mapping = {'G':'C', 'C':'G', 'T':'A', 'A':'U'}
rna_strand = ''
for char in dna_strand:
rna_strand += mapping[char]
return rna_strand
Output:
RNA transcript= UGGACUGA
我一直在嘗試做的是從 DNA 序列列表中獲取 RNA 轉錄列表。 我已經嘗試修改上面的代碼,但我無法實現任何解決方案。 我想知道你是否可以幫我解決這個問題。
輸入將是:
dna1= ['ACCTGACT','AATTGTCT']
預期結果:
rna1 = ['UGGACUGA','UUAACAGA']
您可以使用List Comprehension
:
In [623]: def to_rna(dna_strand):
...: mapping = {'G':'C', 'C':'G', 'T':'A', 'A':'U'}
...: rna_strand = ''
...: for char in dna_strand:
...: rna_strand += mapping[char]
...: return rna_strand
...:
In [626]: rna1 = [to_rna(i) for i in dna1]
In [627]: rna1
Out[627]: ['UGGACUGA', 'UUAACAGA']
以上等價於for
循環:
In [630]: rna1 = []
In [631]: for i in dna1:
...: rna1.append(to_rna(i))
...:
In [632]: rna1
Out[632]: ['UGGACUGA', 'UUAACAGA']
mapping = {'G':'C', 'C':'G', 'T':'A', 'A':'U'}
dna1= ['ACCTGACT','AATTGTCT']
rna_word_list = [
"".join((mapping[dna_char] for dna_char in dna_word))
for dna_word in dna1
]
print(rna_word_list)
['UGGACUGA', 'UUAACAGA']
這是 map function 的主要示例。 “map”接受一個 function f 和一個列表 l 並將 f 應用於 l 的每個元素。 在你的情況下
dnas = ['ACCTGACT' , 'ATTA']
mapping = {'G':'C', 'C':'G', 'T':'A', 'A':'U'}
def to_rna(dna):
return ''.join(map(lambda x: mapping[x], dna))
rnas = list(map(to_rna, dnas))
print(rnas)
使用 integer 鍵的內置translate
,這比您的自定義方法和其他答案快得多(40 倍)
table = {71: 67, 67: 71, 84: 65, 65: 85}
dna = 'ACCTGACT'
assert dna.translate(table) == 'UGGACUGA'
例如:
$ python -m timeit "table = <table>; x = 'gctaatcg'*N" '<method>'
在哪里
JOIN_MAP =>
table = None
method = "".join(table[c] for c in x)
TRLT_STR =>
table = {'g': 'c', 'c': 'g', 't': 'a', 'a': 'u'}
method = x.translate(table)
TRLT_ORD =>
table = {ord('g'): ord('c'), ord('c'): ord('g'), ord('t'): ord('a'), ord('a'): ord('u')}
method = x.translate(table)
在最近的 MacBook 上使用Python 3.9.0
運行上述代碼:
N = 1000
TRLT_ORD 20000 loops, best of 5: 10.3 usec per loop
TRLT_STR 500 loops, best of 5: 394 usec per loop
JOIN_MAP 500 loops, best of 5: 401 usec per loop
例如最快的版本:
$ python -m timeit "table = {ord('g'): ord('c'), ord('c'): ord('g'), ord('t'): ord('a'), ord('a'): ord('u')}; x = 'gctaatcg'*1000" 'x.translate(table)'
請注意,對於小數字,它並不重要
N = 1
TRLT_STR 500000 loops, best of 5: 406 nsec per loop
TRLT_ORD 500000 loops, best of 5: 641 nsec per loop
JOIN_MAP 500000 loops, best of 5: 931 nsec per loop
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.